gpt4 book ai didi

Ruby Koans 计分项目

转载 作者:数据小太阳 更新时间:2023-10-29 08:17:40 25 4
gpt4 key购买 nike

我正在研究 Ruby Koans,我在弄清楚我编写的方法出了什么问题时遇到了一些麻烦。我在about_scoring_project.rb中,写了骰子游戏的计分方法:

def score(dice)
return 0 if dice == []
sum = 0
rolls = dice.inject(Hash.new(0)) { |result, element| result[element] += 1; result; }
rolls.each { |key, value|
# special condition for rolls of 1
if key == 1
sum += 1000 | value -= 3 if value >= 3
sum += 100*value
next
end
sum += 100*key | value -= 3 if value >= 3
sum += 50*value if key == 5 && value > 0
}
return sum
end

对于那些不熟悉这个练习的人:

Greed is a dice game where you roll up to five dice to accumulate points. The following "score" function will be used to calculate the score of a single roll of the dice.

A greed roll is scored as follows:

  • A set of three ones is 1000 points

  • A set of three numbers (other than ones) is worth 100 times the number. (e.g. three fives is 500 points).

  • A one (that is not part of a set of three) is worth 100 points.

  • A five (that is not part of a set of three) is worth 50 points.

  • Everything else is worth 0 points.

Examples:

score([1,1,1,5,1]) => 1150 points score([2,3,4,6,2]) => 0 points score([3,4,5,3,3]) => 350 points score([1,5,1,2,4]) => 250 points

More scoring examples are given in the tests below:

Your goal is to write the score method.

当我尝试运行文件中的最后一个测试时遇到了麻烦:assert_equal 550, score([5,5,5,5])

出于某种原因,我返回 551 而不是 550。感谢您的帮助!

最佳答案

这是我的方法:

def score(dice)
# Count how many what
clusters = dice.reduce(Hash.new(0)) {|hash, num| hash[num] += 1; hash }

# Since 1's are special, handle them first
ones = clusters.delete(1) || 0
score = ones % 3 * 100 + ones / 3 * 1000

# Then singular 5's
score += clusters[5] % 3 * 50

# Then the triples other than triple-one
clusters.reduce(score) {|s, (num, count)| s + count / 3 * num * 100 }
end

关于Ruby Koans 计分项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11603477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com