gpt4 book ai didi

ruby - 石头,纸。剪刀锦标赛

转载 作者:数据小太阳 更新时间:2023-10-29 08:23:56 26 4
gpt4 key购买 nike

我需要实现一个石头剪刀布锦标赛模拟器,它将玩完所有回合并返回锦标赛。

这是我的锦标赛数组:

tournament = [
[
[
["Armando", "P"], ["Dave", "S"]
],
[
["Richard", "R"], ["Michael", "S"]

],
],
[
[ ["Allen", "S"], ["Omer", "P"] ],
[ ["David E.", "R"], ["Richard X.", "P"] ]
]
]

例如 ["Richard", "R"], ["Michael", "S"] 表示理查德玩剪刀石头布的游戏。理查德应该是获胜者并晋级下一轮。

我正在尝试为此实现一个递归函数,但我无法正确设置数组

这是我的方法:

 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

最佳答案

在递归时我们必须考虑两种情况:

要么 rps_tournament_winner 的参数是游戏,要么 rps_tournament_winner 的参数是锦标赛。请注意,锦标赛的一部分本身就是一场锦标赛(只是少了一轮)。如果这是一场比赛,我们会返回获胜者。如果它是一个小节/锦标赛,我们递归找到它的两个 child 的赢家。

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

这是否有助于您理解?

关于 ruby - 石头,纸。剪刀锦标赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14388700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com