我正在写一个小猜谜游戏。我正在写一个点计算算法。
我写了以下内容,它有效。但我觉得我正在将程序背景带入Ruby,或者没有正确地利用Ruby。
经验丰富的Ruby程序员如何解决问题?您可以在TryRuby.com上测试代码(在浏览器解释器中复制和粘贴代码)。
# g = guesses
g = [{ id: 1, elmer: 5, roger: 7, outcome: "Roger Win" },{ id: 2, elmer: 5, roger: 1, outcome: "Elmer Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }]
# r = actual results
r = [{ id: 1, elmer: 3, roger: 9, outcome: "Roger Win" },{ id: 2, elmer: 7, roger: 9, outcome: "Roger Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }]
# points table
p = []
# rules: correct outcome = 1 point, perfect match = 5 points.
# Loop over results.
r.each do |result|
# Loop over guesses.
g.each do |guess|
# Make sure we compare corresponding ids.
# So, compare result 1 to guess 1, r2 to g2, etc....
if result[:id] == guess[:id]
# Init a hash to store score
score = {}
# Did they guess the correct outcome?
if result[:outcome] == guess[:outcome]
# Correct outcome guessed! Make a score hash, give'em a point.
score[:id] = result[:id] # game id
score[:points] = 1 # point
# Was it a perfect match?
if result[:elmer] == guess[:elmer] && result[:roger] == guess[:roger]
# Perfect match! Give them 4 points.
# They already got 1 point for guessing the correct outcome.
score[:points] += 4
end
end
# Add the score to the points table
p.push(score) unless score.empty?
end
end
end
答案 0 :(得分:1)
这对你来说如何?
g.zip(r).collect do |guess, result|
points = (guess == result) ? 5 : guess[:outcome] == result[:outcome] ? 1 : 0
{:id => guess[:id], :points => points}
end
注意:这假定g和r按以下顺序排序:id;如果没有,你可以在这之前排序=)
另外,我会定义:FULL_SCORE = 5
和CORRECT_OUTCOME_SCORE = 1