0

I don't understand what's going on with the solutions to the voter preference and tabulate functions. I had set up a similar function to the answer with the exception that I had

[voter][i] = rank;

Because I thought that the index for the candidate would be the same index for the voter preference and we would put the rank as the actual element in that spot. So candidate 0 would have whatever rank they were given when the voter puts it in.

But the code here has it inversed.

            preferences[voter][rank] = i;

So I'm really stuck on the logic here. If we start with candidate 0 and the name matches, then we would set the rank equal to 0 for that candidate preference? What if the voter is 0 and they rank candidate zero at 3 and then we set it equal to 0 to match the candidate, what is happening? Is the rank actually an index so that a rank of 3 is the array position and then the candidate index is the value we put in the array?

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

  for(int i = 0; i<candidate_count;i++)
{
    if(strcmp(candidates[i].name, name) == 0) //do these match thats all
    {
        preferences[voter][rank] = i;
             return true;
    }
}
  return false;

}
0

That part of the code executes every vote each voter sends. They are identified in the arguments of the function: bool vote(int voter, int rank, string name) in which 'voter' is the voter number, 'rank' is the order in which the voter put his candidate when he voted, and name the name of the candidate. The function goes for the list of candidates checking that the candidate exist, and if he does, it assigns his (the candidate) number to the voter preferences: preferences[voter][rank] = i;.

I hope it helps.

| improve this answer | |
  • Thank you, this clears up the logic perfectly. Though where I'm still confused is with the actual syntax. I thought that setting it equal to i we would be changing the number in rank to the new number i? Instead the whole preferences array is set to an integer, is this because to change the elements in an array we need completely different syntax? – Mike S May 2 at 7:00

You must log in to answer this question.

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