I have an array of six players. This means that I have fifteen unique games:
players = [1, 2, 3, 4, 5, 6]
games = players.combination(2).to_a
I want to organize these games at random in 5 rounds 3. Each player must play 1 game in each round, and no pair should repeat from the previous round.
In each round, I tried to choose player1and player2randomly, using the loop whileassociated with each, but I always find myself in an infinite loop. Any suggestions?
So here is the code (sorry for not putting it in the eariler). The problem is that sometimes it works and gives me the result that I want, but sometimes it just breaks and gets into the loop.
def pick_pair(players)
player1 = players[rand(players.length)]
players.delete(player1)
player2 = players[rand(players.length)]
players.delete(player2)
pair = [player1, player2]
return pair.sort!
end
def check_round(all_rounds, current_round)
repeat = false
if all_rounds == []
repeat = false
else
repeat = catch :repeat do
k = 0
all_rounds.each do |round|
a_r_l = all_rounds.length
round.each do |pair|
r_l = round.length
k += 1
z = 0
current_round.each do |new_pair|
z += 1
if pair == new_pair
repeat = true
throw :repeat, repeat
elsif (k == a_r_l*r_l and z == current_round.length and pair != new_pair)
repeat = false
throw :repeat, repeat
end
end
end
end
end
end
return repeat
end
players = [1,2,3,4,5,6]
all_rounds = []
for i in 1..(players.length-1)
players_d = players.dup
current_round = catch :round do
check = true
while check
current_round = []
for j in 1..(players.length/2)
pair = pick_pair(players_d)
current_round << pair
end
p "Previous rounds: #{all_rounds}"
p "Current round: #{current_round}"
repeat = check_round(all_rounds, current_round)
if repeat == false
throw :round, current_round
else
players_d = players.dup
end
end
end
all_rounds << current_round
end
Hey,
thanks for the help. I rewrote the code and it seems to work. It is also much simpler:
players = [1,2,3,4,5,6]
possible_games = players.combination(2).to_a
all_games = []
for i in 1..(players.length - 1)
round = catch :round do
check = true
while check
round = []
for i in 1..(players.length/2)
pair = possible_games[rand(possible_games.length)]
round << pair
end
if round.flatten.uniq == round.flatten
round.each do |game|
possible_games.delete(game)
end
throw :round, round
else
end
end
end
all_games << round.sort!
end
p all_games