0

My sort_pairs function fails the check50 **:( sort_pairs sorts pairs of candidates by margin of victory ** test however it passes the usage case given on the CS50 website. In the pair type def, I added pair.amount and set it equal to preferences[i][j] in order to record the strength of victory in the add pairs function, rather than in the sort pairs. I felt this made the code cleaner, but I'm really not sure why its failing this test. I have added both codes bellow, let me know if you see anything I'm not!

void add_pairs(void)
{
    for (int i = 0; i < candidate_count; i++)
    {
            for (int j = i + 1 ; j < candidate_count; j++)
            {
                if (preferences[i][j] != preferences[j][i])
                {
                    pair p; 
                    if ( preferences[i][j] > preferences[j][i])
                    {
                        p.winner = i; 
                        p.loser = j; 
                        p.amount = preferences[i][j]; 
                    }
                    else 
                    {
                        p.winner = j; 
                        p.loser = i; 
                        p.amount = preferences[j][i]; 
                    }
                    
                    pairs[pair_count++] = p;
                }
            }
    }
    return;
}

void sort_pairs(void)
{
    
    // selection sort
    for (int i = 0; i < pair_count; i++)
    {
        for (int j = i +1; j < pair_count; j++)
        {
            if (pairs[i].amount < pairs[j].amount)
            {
                pair temp = pairs[i];
                pairs[i] = pairs[j]; 
                pairs[j] = temp;
            }
        }
    }
    return;
}

You must log in to answer this question.

Browse other questions tagged .