这是 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/