你能帮我重构一下我为Ruby Koans#182提出的解决方案吗?这是你在其中写一个分数方法来计算贪婪游戏的分数的公案.以下代码工作,所有测试都通过.
然而,感觉很长,没有红宝石般的感觉.我怎样才能让它变得更好?
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
Run Code Online (Sandbox Code Playgroud)
小智 6
我在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
Run Code Online (Sandbox Code Playgroud)
注意:
.reduce是...的同义词.inject
| 归档时间: |
|
| 查看次数: |
559 次 |
| 最近记录: |