this works for me but I don’t understand how it works at all. Could anyone explain?
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));
}
}
What’s the trick with modulo?
I’m not sure why this would be using
teams_count-1instead ofteams_count, but in general, the modulus is making it “wrap around” so that ifround+matchis greater than the last team number, it will wrap back ground to one of the first teams instead of going past the last team.The way
awayis handled, is a bit special. The % operator doesn’t wrap around the way you want when you have negative numbers. For example-1 % 5gives you-1instead of4. A trick to get around this problem is to add your divisor.(-1+5)%5gives you 4.Let’s rework the code a little to make it clearer. First I’ll use another variable
nto represent the number of teams (again I’m not sure why teams_count-1 is used for this in your code):Then I’ll reorganize the
awaycalculation a little:It should now be clearer that the home team is starting with the current round and then adding the match, while the away team is starting with the current round and subtracting the match. The
% nmakes it wrap around, and the+ nforawaymakes it wrap around properly with negative numbers