我正在担任儿童游戏的足球比赛经理。 可能会有很多回合,每个回合中的每个团队都会互相对抗。 给定每个回合的组合,我需要比赛日历,并且同时进行比赛的团队数量最多。 有没有一种方法可以对组合数组进行排序以达到结果?
我试图“制作”某种算法,但找不到最佳算法。 在提供的代码中,保证两个团队可以同时玩,但不能再玩了。
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
答案 0 :(得分:1)
谷歌搜索条件提示我来了这个解决方案,非常感谢!
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)
end