0

Here's the function i wrote:

bool vote(int voter, int rank, string name)
{

    int t = 0;
    int a = 0;
    for (int i = 0; i < candidate_count; i++)
    {
        int x = strcmp(candidates[i].name, name);
        if (x == 0)
        {
            t++;
        }
    }
    if (t != 0)
    {
        for (int i = 0; i < voter_count; i++)
        {
            for (int j = 0; j < candidate_count; j++)
            {
                int y = strcmp(candidates[j].name, name);
                if (y == 0)
                {
                    a = j;
                    preferences[i][j] = a;
                }
            }
        }
        return true;
    }
    else
    {
        return false;
    }
}

Here's what i am thinking, the first loop iterates over i till all the voters have made their preferences. The second loop iterates over j till all the candidates have been assigned their priority. If the name entered by the voter matches the jth candidate, the preference [i][j] is set as j.

Though i know my logic is a faulty, i can't understand how to execute the correct logic.

1

vote receives a voter number, the currently processed rank, and a candidate's name.

Since the first index to preferences is the voter number, and the second is the rank, you should use those.

The only loop you need here is one for finding the candidate's index, as that's what should be stored in preferences.

| improve this answer | |
  • But, how do i set the value of a two dimensional array with only one loop? – Musical_Ant Mar 11 at 17:28
  • You set one element at a time. A single element in the large array, as vote is called once for each voter/rank combination separately. – Blauelf Mar 11 at 18:05
  • I got it, we are entering the voter and candidate number as an input, and don't need to run loops for them. – Musical_Ant Mar 12 at 7:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .