gpt4 book ai didi

arrays - 在 Ruby 中对组合进行排序

转载 作者:数据小太阳 更新时间:2023-10-29 07:53:27 26 4
gpt4 key购买 nike

我正在尝试根据球队的 ID 创建一个赛季的赛程表。共有 20 支球队,每周任何一支球队只能参加一次比赛。因此,对于第一周,固定装置将是 (1, 2), (3, 4), (5, 6), ..., (19, 20)。然后是第二周,(1, 3), (2, 4), (5, 7), ..., (18, 20)。

是否有某种我可以使用的公式可以轻松解决固定装置问题?也许组合不是在这里使用的最佳选择。解决此问题的最佳方法是什么?

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

最佳答案

听起来您正在尝试安排循环赛中的球队。维基百科描述了一种您可以使用的算法 - 请参阅 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

关于arrays - 在 Ruby 中对组合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14366126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com