Daniel Karcz
Daniel Karcz

Reputation: 1

CS50x, pset3 tideman, vote, preferences

Hi these are my functions for Tideman pset3, the problem is that when I run check50, it says that the vote function did not correctly set ranks and preferences did not correctly set preference for first voter.

However it then checks that record_preferences correctly sets preferences for all voters, which allows other functions work correctly because they are dependant on correct set of preferences array.

From what I see the tests are designed that they want me to use the array ranks this way: ranks[rank] = i;

However I dont understand the preferences function because I checkced every rows with printf after each voter and it seems to be right.

// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcasecmp(name, candidates[i]) == 0)
        {
            ranks[i] = rank;
            rank++;
            return true;
        }
    }
    return false;
}

// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
    // TODO
   for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            // reverse logic when comparing ranks, because rank 0 is greater than rank 1 etc..
            if(ranks[i] < ranks[j])
            preferences[i][j]++;
        }
    }
}

Upvotes: 0

Views: 570

Answers (1)

user9035826
user9035826

Reputation:

For each voter, ranks[] contains their preferences. ranks[i]=j means the jth candidate is ranked the ith position by this voter. In your vote function, you have it backwards. It should look as follows:

// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(name, candidates[i]) == 0)
        {
            ranks[rank] = i;
            return true;
        }
    }
    return false;
}

In the preferences array preferences[i][j] represents the number of voters who prefer candidate i over candidate j. Given a ranking for all candidates (by a certain voter) saved in array ranks[], if ranks[1]=x and rank[2]=y, it means this voter prefer x over y, hence preferences[x][y] += 1, or preference[rank[1]][rank[2]] += 1. So we can simply loop through all pairs.

// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
    //assume rank[1] and rank[2] are ith and jth candidate
    //it means this voter prefers ith candidate over jth candidate
    //hence we have preferences[i][j]++
    //so, we just need to loop through all the pairs once
    for(int i=0; i < candidate_count-1; i++)
    {
        for(int j=i+1; j < candidate_count; j++)
        {
            preferences[ranks[i]][ranks[j]]++;
        }
    }
    return;
}

Upvotes: 0

Related Questions