使用其他选项改进 for() 循环

Improving for() loops with other options

我有以下代码:

void record_preferences(int ranks[]){                               // Update preferences given one voter's ranks

    for(int i = 0; i < candidate_count; i++){                       //Cycle through candidates
        for(int j = 0; j < candidate_count; j++){                   //Cycle through rank list
            if((i == ranks[j]) && (j != candidate_count - 1)){      //If found and not last candidate
                for(int k = j + 1; k < candidate_count; k++){
                    preferences[i][ranks[k]]++;
                }

            }
        }
    }
    return;
}

看自己做的这个自定义函数,感觉多了for() loop

问题:有没有办法让这段代码更有效率,或者我可以使用递归吗?

我尝试制定如何使用递归,但我卡住了,似乎找不到方法。

无法更改的变量(但如果需要,您可以创建更多变量):

Link to entire code Voting method is Tideman Method

for(int i = 0; i < candidate_count; i++){                       //Cycle through candidates
    for(int j = 0; j < candidate_count; j++){                   //Cycle through rank list
        if((i == ranks[j]) && (j != candidate_count - 1)){      //If found and not last candidate
  1. 我们只在 i == ranks[j] 的情况下做任何工作,因此遍历 i 值是没有用的。相反,我们可以直接验证 ranks[j] 是一个有效值,然后使用它。

  2. 因为我们想跳过j == candidate_count - 1的情况,所以只调整循环边界更简单。

所以:

for(int j = 0; j < candidate_count - 1; j++) { // Cycle through ranks, except the last
    int i = ranks[j]; // consider the one possible candidate
    if (i >= 0 && i < candidate_count) { // if the value is valid

当然可以按照您认为合适的方式重命名变量:)