繁体   English   中英

Koans score_project 和理解所需的方法

[英]Koans score_project and understanding the method needed

我目前正在研究 Ruby Koans,我被困在计分项目上。 首先,我很难评估说明并根据我应该做的事情来布置它。 其次,我不确定我在下面写的方法分数是否走在正确的轨道上。 我的问题是 - 有没有办法更好地理解这些说明? 另外,用我写的评分方法,我仍然没有通过第一次测试。 我想我必须先了解我需要做什么,但我想不通。 感谢任何帮助和简单的解释或指导。

谢谢。

Greed 是一种骰子游戏,您最多可以掷五个骰子来累积点数。 下面的“分数”function将用于计算单次掷骰子的分数。

贪婪卷的得分如下:

一套三个是1000分

一组三个数字(除了一个)的价值是该数字的 100 倍。 (例如三个五是 500 分)。

一个(不是一组三个的一部分)值 100 分。

一个五(不是一组三个的一部分)值 50 分。

其他一切都值得0分。

例子:

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

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

您的目标是编写 score 方法。

def score(dice)

(1..6).each do |num|
amount = dice.count(num)

if amount >= 3
  100 * num
elsif num == 1
  100 * amount
elsif num == 5
  50 * amount
else 
  0
    end
  end
end

# test code for method 

class AboutScoringProject < Neo::Koan
  def test_score_of_an_empty_list_is_zero
  assert_equal 0, score([])
end

def test_score_of_a_single_roll_of_5_is_50
  assert_equal 50, score([5])
end

def test_score_of_a_single_roll_of_1_is_100
  assert_equal 100, score([1])
end

def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores
  assert_equal 300, score([1,5,5,1])
end

def test_score_of_single_2s_3s_4s_and_6s_are_zero
  assert_equal 0, score([2,3,4,6])
end

def test_score_of_a_triple_1_is_1000
  assert_equal 1000, score([1,1,1])
end

def test_score_of_other_triples_is_100x
  assert_equal 200, score([2,2,2])
  assert_equal 300, score([3,3,3])
  assert_equal 400, score([4,4,4])
  assert_equal 500, score([5,5,5])
  assert_equal 600, score([6,6,6])
end

def test_score_of_mixed_is_sum
  assert_equal 250, score([2,5,2,2,3])
  assert_equal 550, score([5,5,5,5])
  assert_equal 1100, score([1,1,1,1])
  assert_equal 1200, score([1,1,1,1,1])
  assert_equal 1150, score([1,1,1,5,1])
end

end

这是我所做的:

def score(dice)
  score = 0
  return score if dice == nil || dice == []
  quantity = dice.inject(Hash.new(0)) {|result,element| result[element] +=1; result}
  score += quantity[1] >= 3 ? 1000 + ((quantity[1] - 3) * 100) : quantity[1] * 100
  score += quantity[5] >= 3 ? 500 + ((quantity[5] - 3) * 50) : quantity[5] * 50
  [2,3,4,6].each {|x| score += x * 100 if quantity[x] >= 3 }
  score
end

您可以使用 hash 作为分数而不是编写 switch-case

def score(dice)
  score_map = {
    1 => 100,
    5 => 50
  }
  cluster = dice.inject(Hash.new(0)) {|hash, number| hash[number] += 1; hash}

  cluster.inject(0) do |sum, (num, count)|
    set_count = count / 3

    sum += num == 1 ? 1000 * set_count : num * 100 * set_count
    sum + (score_map[num] || 0) * (count % 3) # use 0 if score of num dosn't exist
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM