简体   繁体   中英

CS50 Tideman - Add Pair

Im currently working my way through CS50's Tideman problem and I'm up to the add_pairs function. Here my code so far:

// Record pairs of candidates where one is preferred over the other
void add_pairs(void)

{
    for (int i = 0; i < candidate_count; i++) {
        for (int j = 0; j < candidate_count; j++) {
            if (preferences[i][j] > preferences[j][i]) {
                pairs[i].winner = i;
                pairs[i].loser = j;
                pair_count += 1;
            }

        }
    }
    return;
}

My code almost passes but fails one of the add_pairs tests:

:( add_pairs fills pairs array with winning pairs
    add_pairs function did not produce correct pairs

From googling around, I see that a separate else if block must check if preferences[i][j] < preferences[j][i] . Then we assign the winner/loser combination index based off of this additional else/if check.

But I just can't wrap my head around why we need this extra if statement? Doesn't the nested loop above(my code) check all cells inside the table against its reverse index counterpart? Meaning we shouldn't need to check the other else/if condition because we check all possibilities in the first place? For example, if we wanted to check the values at index (0,1) against its reverse counterpart(1,0) - the above nested loop guarantees that both indices are checked against each other by way of the if statement?

Think about an election with 4 candidates, a, b, c, d (indexes 0 through 3 respectively). According to this program:

  • a beats b => pairs[0].winner = a, pairs[0].loser = b
  • a beats c => pairs[0].winner = a, pairs[0].winner = c
  • a beats d => pairs[0].winner = a, pairs[0].winner = d

You see where this is going? The pairs array index is independent of the candidate array index.

The index of the pairs array is independent of the candidates', so you should use another variable as the index, not i or j in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM