gpt4 book ai didi

Ruby Koans 182.重构帮助

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

你能帮我重构我为 Ruby Koans #182 提出的解决方案吗?这是您在其中编写得分方法来计算贪婪游戏分数的公案。以下代码有效,所有测试均通过。

但是,它感觉又长又不像 ruby 。我怎样才能让它变得更好?

def score(dice)
rollGreedRoll = Hash.new
rollRollCount = Hash.new
(1..6).each do |roll|
rollGreedRoll[roll] = roll == 1 ? GreedRoll.new(1000, 100) :
GreedRoll.new( 100 * roll, roll == 5 ? 50 : 0)
rollRollCount[roll] = dice.count { |a| a == roll }
end


score =0


rollRollCount.each_pair do |roll, rollCount|
gr = rollGreedRoll[roll]
if rollCount < 3
score += rollCount * gr.individualPoints
else
score += gr.triplePoints + ((rollCount - 3) * gr.individualPoints)

end
end

return score
end

class GreedRoll
attr_accessor :triplePoints
attr_accessor :individualPoints

def initialize(triplePoints, individualPoints)
@triplePoints = triplePoints
@individualPoints = individualPoints
end
end

最佳答案

我在 https://gist.github.com/1091265 上发布了重构演练。 .最终解决方案如下所示:

def score(dice)
(1..6).collect do |roll|
roll_count = dice.count(roll)
case roll
when 1 : 1000 * (roll_count / 3) + 100 * (roll_count % 3)
when 5 : 500 * (roll_count / 3) + 50 * (roll_count % 3)
else 100 * roll * (roll_count / 3)
end
end.reduce(0) {|sum, n| sum + n}
end

注意:.reduce.inject

的同义词

关于Ruby Koans 182.重构帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6738715/

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