2

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

这是我的锦标赛数组:

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

4

2 回答 2

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

这有助于你理解吗?

于 2013-01-17T23:32:25.733 回答
0

它对我有用。以下是步骤:

  1. 检查锦标赛[0][0] 是否为数组
    1.1 返回游戏获胜者
  2. 如果不是
    2.1 递归调用锦标赛函数检查直到结束谁赢得巡回赛[0]
    2.2 递归调用锦标赛函数检查直到结束谁赢得巡回赛[0]
    2.3 递归调用锦标赛函数检查直到结束谁赢得巡回赛[0] [1]
  3. 项目清单
于 2013-07-15T17:55:35.193 回答