我需要实施一个摇滚,纸张,剪刀锦标赛模拟器,它将播放所有轮次并返回锦标赛。
这是我的锦标赛阵列:
tournament = [
[
[
["Armando", "P"], ["Dave", "S"]
],
[
["Richard", "R"], ["Michael", "S"]
],
],
[
[ ["Allen", "S"], ["Omer", "P"] ],
[ ["David E.", "R"], ["Richard X.", "P"] ]
]
]
例如[" Richard"," R"],[" Michael"," S"]代表理查德的游戏演奏了Rock和Michael Scissors。理查德应该是胜利者并进入下一轮。
我正在尝试为此实现递归函数,但我无法正确获取数组
这是我的方法:
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
我已经为排位赛的胜利者发明了很多阵容,但是无法找到解决方案。 希望您能够帮助我。 谢谢。
编辑:
以下是我在方法的每次迭代中应该得到的内容
在第一轮之后
tournament = [
[
[
["Dave", "S"], ["Richard", "R"]
],
[
["Allen", "S"], ["Richard X.", "P"]
]
]
]
第二轮后:
tournament = [
[
[
["Richard", "R"] , ["Allen", "S"]
]
]
]
得奖
["Richard", "R"]
修改:2
这是完整的代码: http://pastebin.com/gjKfiWLD
答案 0 :(得分:7)
我们需要考虑两种情况:
rps_tournament_winner的论点是游戏,或者rps_tournament_winner的论点是锦标赛。请注意,锦标赛的一个分段本身就是一个锦标赛(仅少一轮)。如果这是一场比赛我们会赢回冠军。如果这是一个小节/锦标赛,我们会争取找到两个孩子的胜利者。
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
这有助于您理解吗?
答案 1 :(得分:0)
它对我有用。以下是步骤: