c++ - 联赛赛程算法讲解

标签 c++ algorithm

这对我有用,但我完全不明白它是如何工作的。谁能解释一下?

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/

相关文章:

C++ - 在没有模板参数的情况下使用模板类中的枚举

algorithm - 如何嘈杂地选择数组的k个最小元素?

algorithm - 如何在给定时间在大表中找到接近的 GPS 坐标

c++ - 两个 std::List 之间的距离

algorithm - 了解 Big Oh Careercup 破解编码面试

c++ - 将 alpha channel 添加到 opencv Mat

c++ - 插入窄字符串到 std::basic_ostream<wchar_t>

c++ - 我想从二维数组 C++ 中打印出一些值

c++ - 对象的构造函数和析构函数

algorithm - 如何贪婪地检查拟阵条件