Ruby Koans 计分项目

标签 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

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

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/

相关文章:

ruby-on-rails - Elasticsearch-rails完成建议器, map 数据,创建索引,建议方法

ruby - 如何在 Win7-64 中修复 (OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed)

ruby - 使用 watir-WebDriver 查找链接的同级

ruby - 扩展 Rake 的测试任务

ruby - 不需要的表单参数被附加到分页链接

javascript - Rails 3.1 中的第三方脚本缓存

ruby - 在 ruby​​ 中使用 nokogiri 为名称属性指定指定值,提取网站元标记中内容属性的内容?

ruby - 安装假期 gem 时出错

ruby - 一元问号 (?) 运算符的作用是什么?

java - 如何将 JRuby 中的方法调用到我的 Java 代码中?