Ruby Koans评分项目

时间:2012-07-22 19:49:41

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

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

  

贪婪是一个骰子游戏,你可以累积五个骰子   点。以下“得分”函数将用于计算   骰子的一卷得分。

     

贪婪名单评分如下:

     
      
  • 一组三个是1000分

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

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

  •   
  • 五分(不属于三分之一)值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.感谢您的帮助!

14 个答案:

答案 0 :(得分:3)

这是我的方法:

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

答案 1 :(得分:2)

这是因为您确实将|运算符(按位OR)的结果添加到总分中:

sum += 100*key | value -= 3 if value >= 3 # This is 501 in your case

证明:

irb(main):004:0> value = 4
=> 4
irb(main):005:0> 100 * 5 | value -= 3 # This should be read as (500) | 1 which is 501
=> 501

所以重写如下:

if value >= 3
  sum += 100 * key
  value -= 3
end

答案 2 :(得分:2)

我去了

def score(dice)
  dice.uniq.map do |die|
    count = dice.count die
    if count > 2
      count -= 3
      die == 1 ? 1000 : 100 * die
    else 0
    end + case die
          when 1 then count * 100
          when 5 then count * 50
          else 0
          end
  end.inject(:+) || 0
end

答案 3 :(得分:1)

我的方法是:

def score(dice)
  calculator = ->(no, group_multipler, individual_multipler) { (no / 3 * group_multipler) + (no % 3 * individual_multipler) }
  dice.group_by {|i| i % 7 }.inject(0) do |total, (value, scores)|
    group_multipler, individual_multipler = case value
    when 1
      [1000, 100]
    when 5
      [500, 50]
    else 
      [value * 100, 0]
    end
    total += calculator.call(scores.size, group_multipler, individual_multipler)
  end
end

答案 4 :(得分:1)

这是我的答案:

def score(dice)
  frequency = dice.inject(Hash.new(0)) do |h, el|
    h[el] += 1
    h
  end

  score_triples = { 1 => 1000 }
  score_singles = { 1 => 100, 5 => 50 }

  score = 0
  frequency.each do |k, v|
    score += v / 3 * score_triples.fetch(k, 100 * k)
    score += v % 3 * score_singles.fetch(k, 0)
  end
  score
end

答案 5 :(得分:1)

我的方法使用整数除法和模数除法:

def score(dice)
    points = 1000 * (dice.count(1) / 3)
    points += 100 * (dice.count(1) % 3)
    points += 50 * (dice.count(5) % 3)
    (2..6).each do |i|
        points += (100 * i) * (dice.count(i) / 3)
    end
    points
end

答案 6 :(得分:1)

我的方法使用两个查找表 - 一个包含三元组的分数,另一个包含单曲的分数。我使用表格计算每个数字的分数,并使用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

答案 7 :(得分:0)

我的方法:

     def score(dice)
        score = 0
        score += dice.count(1) >= 3? (1000+ (dice.count(1) -3)*100): dice.count(1) * 100
        score += dice.count(5) >= 3 ? (500 + (dice.count(5) -3)*50): dice.count(5) * 50
       [2,3,4,6].each {|x| dice.count(x) >=3? score+= x*100:0}
       return score
    end

答案 8 :(得分:0)

这是我的解决方案。

SwitchCell switch;

TableView tvProfile = new TableView
        {
            HasUnevenRows = true,
            Intent = TableIntent.Form,
            Root = new TableRoot {
                new TableSection ("Active")
                {
                    (switch = new  SwitchCell {Text = "Pause Timer" } )
                }
            }
        };

switch.OnChanged += (s,e) => {
  // handler logic goes here
};

答案 9 :(得分:0)

    def score(dice)
  # Set up rules Hash
  rules = { 1 => {:triples => 1000, :singles => 100}, 5 => {:triples => 100, :singles => 50} }
  [2,3,4,6].each {|i| rules[i] = {:triples => 100, :singles => 0} }
  # Count all ocourencies
  counts = dice.each_with_object(Hash.new(0)) {|e, h| h[e] += 1}

  #calculate total
  total = 0
  counts.each_pair{ | key, value | 
    total += value >= 3? (rules[key][:triples]*key + (value -3)*rules[key][:singles]): value * rules[key][:singles]
  }
  return total
end

答案 10 :(得分:0)

这是我自己编写的第一段代码(当然,在大量的stackoverflow的帮助下。)看完所有其他答案后,我意识到这特别过分,因为它适用于9个数字骰子(确实存在吗?)

//Getting the name and email from the DOM
let fullName = document.getElementById('fullname').value
let email = document.getElementById('emailaddress').value
//Getting the button from the DOM
let submitButton = document.getElementById('button') 

//Add event listener on click to the button - notice i added the event as argument to the function
submitButton.addEventListener('click', function(event){

    //prevent the reload of the page. here i prevent the event.
    event.preventDefault()

    //Sending the email with the name and email
    emailjs.send("gmail", "yourjourney", {
        "from_name": fullName,
        "from_email": email,
    })
        .then(
            function (response) {
                console.log("SUCCESS", response);
                
            },
            function (error) {
                console.log("FAILED", error);
                
            }

        );
})

答案 11 :(得分:0)

花了29行,但这是我的第一个Ruby

    def score(dice)
      return 0 if dice == [] 
      sums = Array.new  # To hold number of occurrences 1 - 6
      for i in 0..6     # Initialize to 0... note [0] is not used 
        sums[i] = 0
      end
      total = 0   # To hold total
      dice.each do |dots|   # Number of dots showing on dice
        sums[dots] += 1     # Increment the array members 1 - 6
      end 
        if sums[1] > 2 then # If 3 1's
          total += 1000 
          sums[1] -= 3   # Remove the 3 you took, in case there's more
        end
        if sums[2] > 2  then total += 200  # If 3 2's
        end
        if sums[3] > 2  then total += 300   #If 3 3's
        end
        if sums[4] > 2  then total += 400    #If 3 4's
        end
        if sums[5] > 2  then total += 500     #If 3 5's
          sums[5] -= 3                        #Remove the 5's you took
        end
        if sums[6] > 2  then total += 600  #If 3 6's
        end
     total += (sums[1] * 100)   # If any ones are left
     total += (sums[5] * 50)    # Same for fives
     return total
end

答案 12 :(得分:-1)

def score(dice)
    score = 0
    dice.uniq.each do |number|
        count = dice.count number
        weight = if number == 1 then 10 else number end
        if count >= 3
            score += weight * 100
            count -= 3
        end
        if count > 0 and number == 1 or number == 5
            score += count * weight * 10
        end
    end
    score
end

答案 13 :(得分:-2)

+------------------------------------------------------+
| concat('{',group_concat(g_id,':{',gc,'}'),'}')       |
+------------------------------------------------------+
| {1234:{158990:30,158991:60},3211:{9988:-55,9989:65}} |
+------------------------------------------------------+
1 row in set (0.04 sec)