2012-09-19 18 views
0

這對我有用,但我不明白它是如何工作的。誰能解釋一下?聯賽夾具算法說明

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)); 
    } 
} 

模數的竅門是什麼?

+0

你確定這應該是'%(teams_count-1)'而不是'%teams_count'? –

+0

我真的不知道。我只是在網絡的某個地方發現了這個代碼。它適合我。 – micnyk

+0

看起來似乎寫道,最後一支球隊永遠不會成爲比賽的一部分,除非特殊情況下最後一支球隊是第一場比賽的客隊。也許這對於這個聯盟來說是正確的行爲,但這似乎有點奇怪。 –

回答

4

我不知道爲什麼會被使用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使它環繞,+ naway使它正確環繞與負數