Just as part of my hobby, I'm try to build a scheduler where you enter N number of players in the system, and it will generate an array of combinations. For example
players = ['A','B','C','D','E']
players.combination(2).to_a
# ["A", "B"], ["A", "C"], ["A", "D"], ["A", "E"], ["B", "C"], ["B", "D"], ["B", "E"], ["C", "D"], ["C", "E"], ["D", "E"]]
Then I would like my generate_matches functions to take this array of pairs, and turn this into matches where teach pair only plays once AND players of course cannot play themselves. This should work on a minimum 4 players, and work for every number above 4 whether it's odd or even.
I thought of it to be a simple issue to solve, but I've been just in a rabbit hole.
See pseudocode & code below:
# select random team
# find team that does not contain one of the players
# create match between team 1 and team 2
# delete team 1 and team 2 from original array
# repeat until no team left
def generate_matches(player_combinations)
matches = []
while !player_combinations.empty?
team_1 = player_combinations.shift
# if team doesn't include any of the team 1 player, select them
filtered_teams = player_combinations.select do |team|
(team & team_1).empty?
end
team_2 = filtered_teams.pop
player_combinations.delete(team_2)
matches << [team_1, team_2]
end
matches
end
Expected Result:
[
[['C','B'], ['A','E']],
[['E','D'], ['B','A']],
[['A','C'], ['D','B']],
[['B','E'], ['C','D']],
[['D','A'], ['E','C']],
]
Actual Result:
[
[["A", "C"], ["D", "E"]],
[["C", "D"], ["B", "E"]],
[["A", "B"], ["C", "E"]],
[["B", "C"], ["A", "E"]]
]
This should result in equal amount of matches for players, however it doesn't. I'm really confused why. See results after running it a few times:
Key Represents Player
Value represents # games they played
{"A"=>4, "C"=>3, "B"=>2, "E"=>4, "D"=>3}
But it should actually be:
{"A"=>4, "C"=>4, "B"=>4, "E"=>4, "D"=>4}
Sometimes it's just dumb luck, and I do get the correct answer. Most of the times, I don't. I guess I think too simple about this problem