ruby - 生日巧克力 HACKERRANK RUBY

标签 ruby

这是 hackerrank 中问题的原始链接:https://www.hackerrank.com/challenges/the-birthday-bar/problem

我一直在 Ruby 中解决这个问题,我不知道为什么我的计数器总是返回 1。这就是解决方案。我希望你能帮助我理解我做错了什么。

s = [1, 2, 1, 3, 2]
d = 3
m = 2


def birthday(s, d, m)
    array = []
    cont = 0
    sum = 0
    m.times {array.push(s.shift)}
    (m-1).times do
        array.each {|i| sum = sum + i}
        if sum == d
            cont += 1 
        end
        array.shift
        array.push(s.shift)    
    end
    return cont
end

birthday(s, d, m)

最佳答案

虽然以下内容没有直接回答您的问题,但它是一种类似于 Ruby 的解决问题的方式,特别是使用 Enumerable#each_cons 方法和 Enumerable#count .

def birthday(s, d, m)
  s.each_cons(m).count { |a| a.sum == d }
end
s = [1, 2, 1, 3, 2]
d = 3
m = 2    
birthday(s, d, m)
  #=> 2 ([1, 2] and [2, ])
s = [2, 2, 1, 3, 2]
d = 4
m = 2
birthday(s, d, m)
  #=> 2 ([2, 2] and [1, 3])
s = [2, 4, 3, 2, 1, 2, 6, 1]
d = 9
m = 3
birthday(s, d, m)
  #=> 4 ([2, 4, 3], [4, 3, 2], [1, 2, 6] and [2, 6, 1])

来自文档的通知,当 each_cons在没有 block 的情况下使用它会返回一个枚举器:

s = [1, 2, 1, 3, 2]
d = 3
m = 2
enum = s.each_cons(m)
  #=> #<Enumerator: [1, 2, 1, 3, 2]:each_cons(2)> 

enum将生成元素并将它们传递给 count直到没有更多的内容可以生成,此时它会引发 StopIteration异常(exception):

enum.next #=> [1, 2] 
enum.next #=> [2, 1] 
enum.next #=> [1, 3] 
enum.next #=> [3, 2] 
enum.next #=> StopIteration (iteration reached an end) <exception>

我们可以写1:

enum.count { |a| a.sum == d }
  #=> 2 

enum之后生成 block 变量 [1, 2] 的第一个值 ( a )被赋值:

a = enum.next
  #=> [1, 2]

并执行分块计算。作为

a.sum == d
  #=> [1, 2].sum == 3 => true

计数(从零开始)加一。 enum然后将其每个剩余值传递给 count并且重复该过程。例如,当[1, 3].sum == 3 => false时执行后,计数不增加。

1。请注意,因为我刚刚遍历了 enum 的所有元素。 , enum.next将生成另一个 StopIteration异常(exception)。执行enum.count { |a| a.sum == d }因此,我必须首先重新定义枚举器( enum = s.each_cons(m) )或 Enumerator#rewind它:enum.rewind .

关于ruby - 生日巧克力 HACKERRANK RUBY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63893582/

相关文章:

ruby-on-rails - 搜索查询中指定时区

当单元格/字段包含前导双引号时,Ruby 不会解析 CSV

ruby-on-rails - respond_to block 总是渲染 html

ruby - 限制 Net::HTTP.request_get 的获取大小

ruby - 有没有办法在ruby中随机调用特定类的方法?

ruby-on-rails - Ruby:比较两个哈希值

ruby-on-rails - 在 RoR : Which one to use out of redirect_to and head :moved_permanently? 中重定向

ruby-on-rails - 如何在一个 View 中对两个表进行分页

ruby - 带有nio4r select循环的Ruby套接字

mysql - 如何将 mysql2 连接到 Ruby on Rails?