1

我是 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循环的终止条件需要注意。

有什么帮助吗?

4

1 回答 1

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"]

于 2012-10-10T20:05:09.540 回答