2012-07-29 41 views
1

我是Ruby的新手,並且正在嘗試使用該語言來實施一個剪紙比賽。在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循環的終止條件需要注意。

任何幫助?

+1

建議:使用更多的表達式映射/選擇/ ...和較少的語句爲/每個。 – tokland 2012-07-29 14:13:42

+0

遞歸解決方案可能更容易,尤其是如果您必須處理任意深度的括號。因爲這個標記爲「家庭作業」,所以我暫且放棄。 – 2012-07-29 12:51:52

回答

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"]結果。