使用其他选项改进 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
。
问题:有没有办法让这段代码更有效率,或者我可以使用递归吗?
我尝试制定如何使用递归,但我卡住了,似乎找不到方法。
无法更改的变量(但如果需要,您可以创建更多变量):
candidate_count
是一个全局变量,等于9
preferences[i][j]
是一个全局变量。比候选人 j 更喜欢候选人 i 的选民人数
ranks[]
是局部变量。此变量存储用户输入的候选排名
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
我们只在 i == ranks[j]
的情况下做任何工作,因此遍历 i
值是没有用的。相反,我们可以直接验证 ranks[j]
是一个有效值,然后使用它。
因为我们想跳过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
当然可以按照您认为合适的方式重命名变量:)
我有以下代码:
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
。
问题:有没有办法让这段代码更有效率,或者我可以使用递归吗?
我尝试制定如何使用递归,但我卡住了,似乎找不到方法。
无法更改的变量(但如果需要,您可以创建更多变量):
candidate_count
是一个全局变量,等于9preferences[i][j]
是一个全局变量。比候选人 j 更喜欢候选人 i 的选民人数ranks[]
是局部变量。此变量存储用户输入的候选排名
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
我们只在
i == ranks[j]
的情况下做任何工作,因此遍历i
值是没有用的。相反,我们可以直接验证ranks[j]
是一个有效值,然后使用它。因为我们想跳过
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
当然可以按照您认为合适的方式重命名变量:)