我是Ruby的新手,我正在尝试使用这种语言来实施摇滚剪刀锦标赛,作为练习。
在下面的代码中调用的rps_game_winner方法会在一对竞争对手中返回获胜者。
到目前为止,这是我的尝试:
def rps_tournament_winner(tournament)
qualifying_round_winners = []
for i in 0..0
tournament.each_with_index do |x, xi|
x.each_with_index do |y, yi|
winner = rps_game_winner(y)
qualifying_round_winners.push(winner)
qualifying_round_winners = qualifying_round_winners.each_slice(2).to_a
end
end
tournament = qualifying_round_winners.each_slice(2).to_a
end
return tournament
end
这是我提供的输入:
puts rps_tournament_winner([
[
[ ["Armando", "P"], ["David", "S"] ],
[ ["Richard", "R"], ["Michael", "S"] ]
]
])
我得到的输出是:
David
S
Richard
R
这是我被卡住的地方。我无法让这两个人相互竞争,并宣布最后的胜利者。
正如您在上面的代码中所看到的,for循环的终止条件需要引起注意。
有任何帮助吗?
答案 0 :(得分:2)
我在您的代码中做了一些修改。
注意:如果我将[ ["Armando", "P"], ["David", "S"] ]
作为rps_game_winner()
功能的输入,则会提供["David", "S"]
之类的结果。
def rps_tournament_winner(tournament)
qualifying_round_winners = []
for i in 0..0
tournament.each_with_index do |x, xi|
x.each_with_index do |y, yi|
winner = rps_game_winner(y)
qualifying_round_winners.push(winner)
end
end
tournament = rps_game_winner(qualifying_round_winners)
end
return tournament
end
所以你的输入
[[ [["Armando", "P"], ["David", "S"]], [["Richard", "R"], ["Michael", "S"]] ]]
它还会返回["Richard", "R"]
等结果。