我在给孩子们做足球锦标赛经理。可以有多轮比赛,每轮比赛中的每一支球队都会相互比赛。给出每一轮的组合,我需要比赛的日历,其中最多的球队同时比赛。有没有一种方法可以对组合数组进行排序以获得结果?
我试着“做”一些算法,但是我找不到最好的。在提供的代码中,可以保证两支球队可以同时比赛,但不能超过...
teams = [1,2,3,4,5,6,7,8] # number of teams is variable
pairings = teams.combination(2).to_a
pairings.shuffle!
calendar = []
calendar << pairings.slice!(0)
while pairings.any?
p = calendar.slice(-1)
a = p[0]
b = p[1]
matched = false
pairings.each do |pairing|
next if pairing.include? a
next if pairing.include? b
matched = true
calendar << pairings.delete(pairing)
break
end
unless matched
p1 = pairings.slice!(0)
prev = false
calendar.each do |pairing|
if pairing.include?(a) || pairing.include?(b)
prev = true
next
end
unless prev
i = calendar.index(pairing)
calendar.insert(i, p1)
break
end
prev = false
end
end
end发布于 2019-08-15 21:58:47
在谷歌上搜索了我建议的术语后,我找到了这个解决方案,非常感谢!
teams = [1,2,3,4,5]
teams.push "x" if teams.length.odd?
first = [teams.slice!(0)]
teams.length.times do
half = Integer(teams.length / 2)
row1 = first + teams.slice(0...half)
row2 = teams.slice(half...teams.length).reverse
for i in 0..half do
next if row1[i] == "x"
next if row2[i] == "x"
puts "#{row1[i]} - #{row2[i]}"
end
teams.unshift(teams.pop)
endhttps://stackoverflow.com/questions/57507138
复制相似问题