这对我有用,但我完全不明白它是如何工作的。谁能解释一下?
for(int round = 0; round < rounds_count; round++)
{
for(int match = 0; match < matches_per_round; match++)
{
int home = (round + match) % (teams_count - 1);
int away = (teams_count - 1 - match + round) % (teams_count - 1);
if(match == 0)
away = teams_count - 1;
matches.push_back(Match(&teams[home], &teams[away], round));
}
}
取模有什么诀窍?
最佳答案
我不确定为什么会使用 teams_count-1
而不是 teams_count
,但总的来说,模数使它“环绕”,所以如果round+match
大于最后一个团队编号,它将返回到第一个团队之一,而不是越过最后一个团队。
away
的处理方式有点特殊。当您有负数时,% 运算符不会按照您想要的方式环绕。例如 -1 % 5
给你 -1
而不是 4
。解决这个问题的一个技巧是添加除数。 (-1+5)%5
给你 4。
让我们稍微修改一下代码,让它更清晰。首先,我将使用另一个变量 n
来表示团队的数量(我再次不确定为什么在您的代码中为此使用 teams_count-1):
int n = teams_count-1;
int home = (round + match) % n;
int away = (n - match + round) % n;
然后我将稍微重新组织一下away
计算:
int n = teams_count-1;
int home = (round + match) % n;
int away = (round - match + n) % n;
现在应该更清楚了,主队是从本轮开始,然后加上比赛,而客队是从本轮开始,然后减去比赛。 % n
使其环绕,而 away
的 + n
使其以负数正确环绕
关于c++ - 联赛赛程算法讲解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12498857/