如果有超过8的话,我试图拆分子阵列。我已经尝试在玩家身上调用rps_tournament_winner函数,如果它的扁平长度大于16但是我得到了“堆栈太深的错误”。
我是否必须参与球员变量或锦标赛?我正朝着正确的方向努力;不是一个完整的解决方案。
def rps_tournament_winner(tournament)
return rps_game_winner(tournament) if tournament.flatten.length == 4
players = tournament.flatten(2)
while players.length > 1
players = players.each_slice(2).map { |x| rps_game_winner(x) }
end
players[0]
end
答案 0 :(得分:6)
这是我能够提出的最短时间(带递归)
def rps_tournament_winner(games)
if games.flatten.length > 4
rps_game_winner([rps_tournament_winner(games[0]), rps_tournament_winner(games[1])])
else
rps_game_winner(games)
end
end
答案 1 :(得分:5)
这也是一个优雅的解决方案,不会使阵列扁平化:
def rps_tournament_winner(tournament)
if tournament[0][0].is_a?(Array)
tournament =[rps_tournament_winner(tournament[0]), rps_tournament_winner(tournament[1])]
end
rps_game_winner(tournament)
end
答案 2 :(得分:1)
我使用递归解决了它
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
def rps_game_winner(game)
raise WrongNumberOfPlayersError unless game.length == 2
if game[0][0].is_a?(Array) then
winner1 = rps_game_winner(game[0])
winner2 = rps_game_winner(game[1])
game = [winner1, winner2]
end
raise NoSuchStrategyError unless /^(P|R|S){2}$/ =~ game[0][1] + game[1][1]
case game[0][1]
when "R"
if game[1][1] == "P" then
game[1]
else
game[0]
end
when "P"
if game[1][1] == "S" then
game[1]
else
game[0]
end
when "S"
if game[1][1] == "R" then
game[1]
else
game[0]
end
end
end
def rps_tournament_winner(tournament)
rps_game_winner(tournament)
end
答案 3 :(得分:0)
只有回答此问题才能结束这个问题,希望我的回答能帮助其他人= D
在盯着它看了大约三个小时之后,我的脑子却停止了小睡,我想出了这个:
def rps_tournament_winner(tournament)
return rps_game_winner(tournament) if tournament.flatten.length == 4
if tournament.flatten.length == 16
players = tournament.flatten(2)
else
players = tournament.flatten(4)
end
while players.length > 1
players = players.each_slice(2).map { |x| rps_game_winner(x) }
end
players[0]
end
if 语句允许我检查一个8人或更多玩家的比赛(测试仅适用于8,16和32名玩家,所以我怀疑这适用于较大的套装)我的问题之前我只会 flatten(2)这对于较大的锦标赛来说是行不通的。