2013-01-16 163 views
3

我正在嘗試根據團隊的ID創建一個賽季的工具列表。有20支球隊,每週任何一支球隊只能打一次。因此,對於第一週,燈具將是(1,2),(3,4),(5,6),...,(19,20)。然後第二週,(1,3),(2,4),(5,7),...,(18,20)。在Ruby中對組合進行排序

是否有某種我可以做的公式可以很容易地使用夾具?也許組合不是在這裏使用的最好的東西。什麼是解決這個問題的最好方法?

class FixtutreGenerator 
    a = Array(1..20) 
    i = 0 

    while i < a.combination(2).to_a.length 
    print a.combination(2).to_a[i] 
    i = i + 20 
end 
end 
+0

應該有辦法列出了所有的可能性,但你有沒有考慮有多少?對於20支球隊來說,這個數字將是「(20!)/(10!* 2^10)= 654729075」。你確定你想要一個這麼長的名單嗎?你認爲你的電腦能夠計算出來嗎? – sawa

+0

我希望你意識到你正在通過循環重新計算所有組合*每個*時間。 – tadman

回答

5

這聽起來像你正在嘗試在循環賽中進行團隊排班。維基百科描述了一種您可以使用的算法 - 請參閱http://en.wikipedia.org/wiki/Round-robin_tournament#Scheduling_algorithm

下實現算法進行打印,每星期的配對:

teams = Array(1..20) 
fixed_team = teams.shift #The fixed competitor described in the algorithm 
teams.length.times do |i| 

    #Create the two groups listed in the algorithm 
    teams = teams.rotate 
    week_teams = teams.dup.unshift(fixed_team) 
    first_group, second_group = week_teams.each_slice(week_teams.length/2).to_a 
    second_group.reverse! 
    weeks_pairings = first_group.zip(second_group) 

    #Output the week's pairings 
    puts "Week #{i + 1}: #{weeks_pairings}" 
end 

#Output: 
#=> Week 1: [[1, 2], [3, 20], [4, 19], [5, 18], [6, 17], [7, 16], [8, 15], [9, 14], [10, 13], [11, 12]] 
#=> Week 2: [[1, 3], [4, 2], [5, 20], [6, 19], [7, 18], [8, 17], [9, 16], [10, 15], [11, 14], [12, 13]] 
#=> etc 
+0

明智的答案,正是我所期待的。謝謝 – user1014888