I'm trying to deal with the vote function and there are 2 questions I'd like to seek for your help:
bool vote(int rank, string name, int ranks[])
I don't understand what the rank parameter is for and why is it declared here?
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
for (int j = 0; j < candidate_count; j++)
{
for (int k = 0; k < candidate_count; k++)
{
//Compare the name provided by the user with the name of the candidates numbered jth in the array candidates[MAX] which already populated above
if (strcmp(name, candidates[k]) == 0)
{
ranks[j] = k;
printf("ranks[%d] = %d\n", j, k);
}
}
return true;
}
return false;
}
The result of the printf function as follows (with candidates = {a,b,c}, voter_count = 2):
Rank 1: a, ranks[0] = 0; Rank 2: b, ranks[0] = 1; Rank 3: c, ranks[0] = 2; Rank 1: c, ranks[0] = 2; Rank 2: b, ranks[0] = 1; Rank 3: a, ranks[0] = 0
The value of j in ranks[j] was not updated. How can I resolve this problem?
Thanks so much for your help!
Here is some code:
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[]){
//We want to cycle through the list of candidates given
for(int i = 0; i < candidate_count; i++){
//If the candidate(s) in the array matches with string name, we will continue
if(strcmp(candidates[i], name) == 0){
//This is the tricky part to understand. Read below for answer.
ranks[rank] = i;
return true;
}
}
return false;
}
int rank
represents the user's given rank for the candidate and int i
would the candidate's position in the candidates[]
. We want to update the ranks[]
according to the right rank. This is still quite confusing to understand so here is an example.
We have four candidates: John, Jim, Sam, Alex
In
string candidates[MAX];
, John is atcandidates[0]
, Jim is atcandidates[1]
, Sam is atcandidates[2]
, and Alex is atcandidates[3]
.
Suppose the user gives their vote and they vote in this order:
Let's run it in the bool vote(int rank, string name, int ranks[])
.
vote(j, name, ranks)
where j = 0, name = Alex, and ranks is the ranks[]- We will loop the name Alex until we find it in
candidates[MAX]
.- Alex is found in
candidates[i]
where i = 3.- We want to update the
ranks[]
ranks[rank] = i;
would mean that atranks[rank]
is equal to i which is 3. In other words, ranks[0] is equal to Alex's ith position in thecandidates[MAX]
.
Then you repeat this cycle until all the voter's ranking is done.