Skip to content

Instantly share code, notes, and snippets.

@albertbellonch
Created September 4, 2014 21:56
Show Gist options
  • Save albertbellonch/f8c992ac40beea7efbd0 to your computer and use it in GitHub Desktop.
Save albertbellonch/f8c992ac40beea7efbd0 to your computer and use it in GitHub Desktop.
Ping pong league
#!/usr/bin/env ruby
# Based on: http://en.wikipedia.org/wiki/Round-robin_tournament
def matches_schedule(players_count)
schedule = {}
matchdays = players_count - 1
matches_per_day = middle = players_count / 2
list = (1..players_count).to_a
list_1 = list[0..middle-1]
list_2 = list[middle..players_count-1]
1.upto(matchdays) do |matchday|
schedule[matchday] = matches_per_day.times.map do |i|
[list_1[i], list_2[i]]
end.shuffle
list_2 << list_1.pop
up, *list_2 = list_2
list_1.insert(1, up)
end
schedule
end
# assume players is a list of strings, each containing the name of the player
players << '(descans)' unless players.count % 2 == 0
matches_schedule(players.count).each do |matchday, matches|
puts "======================="
puts "Match day #{matchday}"
puts "======================="
matches.each do |player_1, player_2|
puts "#{players[player_1-1]} - #{players[player_2-1]}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment