Reputation: 3658
I need to implement a rock, paper, scissors tournament simulator which will play all the rounds and return the tournament.
This is my tournament array:
tournament = [
[
[
["Armando", "P"], ["Dave", "S"]
],
[
["Richard", "R"], ["Michael", "S"]
],
],
[
[ ["Allen", "S"], ["Omer", "P"] ],
[ ["David E.", "R"], ["Richard X.", "P"] ]
]
]
where for example ["Richard", "R"], ["Michael", "S"] represents a game where Richard played Rock and Michael Scissors. Richard should be the winner and advance to next round.
I am trying to implement a recursive function for this but i am having trouble getting the arrays right
Here is my method:
def rps_tournament_winner(tournament)
qualifying_round_winners = []
round_winners = []
# last round
if tournament.length < 1
return
end
tournament.each_with_index do |round,i|
puts round.inspect
qualifying_round_winners[i] = []
round_winners = []
round.each_with_index do |game,j|
winner = rps_game_winner(game)
round_winners.push winner
end
qualifying_round_winners[i] = round_winners
end
rps_tournament_winner(qualifying_round_winners)
end
I have invented a lot with the arrays for qualifying winners but cant figure out a solution. Hope you can help me. thank you.
Edit:
Here is what I should get in each iteration of the method
After frist round
tournament = [
[
[
["Dave", "S"], ["Richard", "R"]
],
[
["Allen", "S"], ["Richard X.", "P"]
]
]
]
After second round:
tournament = [
[
[
["Richard", "R"] , ["Allen", "S"]
]
]
]
Winner
["Richard", "R"]
Edit:2
here is the full code: http://pastebin.com/gjKfiWLD
Upvotes: 2
Views: 5092
Reputation: 101
It worked for me. Here are the steps:
Upvotes: 0
Reputation: 472
There are two cases we have to consider as we recurse:
Either rps_tournament_winner's argument is a game or rps_tournament_winner's argument is a tournament. Note that a subsection of a tournament is itself a tournament (just with one fewer round). If it's a game we return the winner. If it's a subsection/tournament we recurse to find the winner of its two children.
def rps_tournament_winner(tournament)
# Check if we're at a game
if tournament[0][0].is_a? String
return rps_game_winner(tournament)
end
# Otherwise keep going down the rabbit hole
return rps_game_winner([rps_tournament_winner(tournament[0]),rps_tournament_winner(tournament[1])])
end
Does this help you understand?
Upvotes: 7