Ruby Koans 评分项目

Max*_*ett 4 ruby

我正在研究 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
Run Code Online (Sandbox Code Playgroud)

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

Greed 是一款骰子游戏,您可以滚动最多五个骰子来累积积分。下面的“score”函数将用于计算单次掷骰子的得分。

贪婪掷骰的得分如下:

  • 一组三个为1000分

  • 一组三个数字(除了 1 之外)的价值是该数字的 100 倍。(例如,三五分等于 500 分)。

  • 一个(不属于一组三个)值 100 分。

  • 5 分(不属于一组 3 分)的得分为 50 分。

  • 其他的都值0分。

例子:

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

下面的测试中给出了更多评分示例:

您的目标是编写得分方法。

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

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

use*_*783 6

我的方法使用两个查找表 - 一个包含三元组的分数,另一个包含单打的分数。我使用表格计算出每个数字的分数,并使用以下方法累积总分inject

def score(dice)
  triple_scores = [1000, 200, 300, 400, 500, 600]
  single_scores = [100, 0, 0, 0, 50, 0]
  (1..6).inject(0) do |score, number|
    count = dice.count(number)
    score += triple_scores[number - 1] * (count / 3)
    score += single_scores[number - 1] * (count % 3)
  end
end
Run Code Online (Sandbox Code Playgroud)


Aet*_*rus 5

这是我的方法:

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
Run Code Online (Sandbox Code Playgroud)

  • 规则没有规定一组三个必须是连续的。:-) (2认同)