CS50 决选:投票算法用于在决选中列出选民的投票偏好
CS50 runoff: voting algorithm to tabulate the voting preferences of voters in a runoff election
我真的很感激有一双新的眼睛来发现我的错误! Preferences 是一个二维数组(选民对偏好),包含每个选民按排名顺序选择的候选人的数量(例如 preference[0][0] = i 表示 i 是第 0 个选民的第一偏好候选人)。我没有包含一个排名循环,因为它只会在候选人被淘汰时增加,并且每次考虑新选民时它都应该恢复为 0。
我已经在这个问题上工作了很长一段时间,但我在 check50 的制表和 print_winner 中仍然遇到一些错误。对于制表,只有在一名候选人被淘汰的情况下才会出现问题。
void tabulate(void)
{
// Set rank to equal zero first.
// This will only change if the voter's first preference is eliminated.
int rank = 0;
// Loop through voters.
for (int voter = 0; voter < voter_count; voter++)
{
for (int i = 0; i < candidate_count; i++)// Loop through candidate possibilities
{
// When candidate has been identified and is not eliminated execute this statement.
if (preferences[voter][rank] == i && candidates[i].eliminated == false)
{
candidates[i].votes += 1;
rank = 0;
// Rank is reset to zero as this may have been increased in the else if statement.
}
else if (preferences[voter][rank] == i && candidates[i].eliminated == true)
{
// If the candidate has been eliminated the rank is increased.
rank += 1;
voter -= 1;
// The voter is decreased so on returning to the 'for' loop the same voter is checked again.
}
}
}
}
这个voter -= 1;
不好。程序仍在 i
循环中,因此请预料到意外情况,因为程序可能会尝试查看 preferences[-1][1]
。
这是一个函数将失败的选举:4 个候选人 a b c d; 5 位选民
voter| votes
1 | b c a d
2 | a d b c
3 | a d b c
4 | d a c b
5 | d a c b
"b" 和 "c" 将被淘汰。在表格中,候选人 "a" 应该得到选民 1 的选票。但他们会吗?由于功能正在遍历候选人,所以没有。当它处理candidate "a"时,既不排名0也不淘汰;它没有得到投票。并且不会再处理。基于此,我认为该程序需要遍历排名而不是候选人。一旦计票,就结束该循环。
我真的很感激有一双新的眼睛来发现我的错误! Preferences 是一个二维数组(选民对偏好),包含每个选民按排名顺序选择的候选人的数量(例如 preference[0][0] = i 表示 i 是第 0 个选民的第一偏好候选人)。我没有包含一个排名循环,因为它只会在候选人被淘汰时增加,并且每次考虑新选民时它都应该恢复为 0。
我已经在这个问题上工作了很长一段时间,但我在 check50 的制表和 print_winner 中仍然遇到一些错误。对于制表,只有在一名候选人被淘汰的情况下才会出现问题。
void tabulate(void)
{
// Set rank to equal zero first.
// This will only change if the voter's first preference is eliminated.
int rank = 0;
// Loop through voters.
for (int voter = 0; voter < voter_count; voter++)
{
for (int i = 0; i < candidate_count; i++)// Loop through candidate possibilities
{
// When candidate has been identified and is not eliminated execute this statement.
if (preferences[voter][rank] == i && candidates[i].eliminated == false)
{
candidates[i].votes += 1;
rank = 0;
// Rank is reset to zero as this may have been increased in the else if statement.
}
else if (preferences[voter][rank] == i && candidates[i].eliminated == true)
{
// If the candidate has been eliminated the rank is increased.
rank += 1;
voter -= 1;
// The voter is decreased so on returning to the 'for' loop the same voter is checked again.
}
}
}
}
这个voter -= 1;
不好。程序仍在 i
循环中,因此请预料到意外情况,因为程序可能会尝试查看 preferences[-1][1]
。
这是一个函数将失败的选举:4 个候选人 a b c d; 5 位选民
voter| votes
1 | b c a d
2 | a d b c
3 | a d b c
4 | d a c b
5 | d a c b
"b" 和 "c" 将被淘汰。在表格中,候选人 "a" 应该得到选民 1 的选票。但他们会吗?由于功能正在遍历候选人,所以没有。当它处理candidate "a"时,既不排名0也不淘汰;它没有得到投票。并且不会再处理。基于此,我认为该程序需要遍历排名而不是候选人。一旦计票,就结束该循环。