在下面的程序中,循环似乎在运行 2 次后停止,而不是预期的 3 次。 sum_of_sums
的预期值为 35,但此处为 23。
ary = [1,2,3,4]
sum_of_sums = 0
ary.each do # => [1, 2, 3, 4]
n=ary.shift # => 1, 2
sum_of_products = ary.reduce(0) do |memo,e| # => [2, 3, 4], [3, 4]
memo+(n*e) # => 2, 5, 9, 6, 14
end
sum_of_sums += sum_of_products # => 9, 23
end
sum_of_sums # => 23
它按预期与[1,2,3]一起工作:
ary = [1,2,3]
sum_of_sums = 0
ary.each do # => [1, 2, 3]
n=ary.shift # => 1, 2
sum_of_products = ary.reduce(0) do |memo,e| # => [2, 3], [3]
memo+(n*e) # => 2, 5, 6
end
sum_of_sums += sum_of_products # => 5, 11
end
sum_of_sums # => 11
我正在尝试编写一个程序,对于一组 [a,b,c,d],计算
ab + ac + ad + bc + bd + cd
。除了通过示例之外,我不知道如何表达这种模式。是的,我可能可以更明确地做到这一点,或者通过分解项来更容易地做到这一点,但我想知道为什么这个循环不起作用!
编辑:谢谢大家...问题似乎是在 #each
循环中使用 #shift
修改了数组。我最终成功了:
ary = [1,2,3,4]
sum = 0
until ary.count==1 do
sum += ary.shift * ary.sum
end
sum
最佳答案
考虑到您的问题已得到解答,我想建议一种更有效的计算方法。请注意
(a+b+c)**2 = a**2 + b**2 + c**2 + 2*(ab + ac + bc)
所以
ab + ac + bc = ((a+b+c)**2 - (a**2 + b**2 + c**2))/2
因此我们可以写
def sum_of_cross_terms(arr)
((arr.sum)**2 - arr.reduce(0) { |t,n| t + n**2 })/2
end
sum_of_cross_terms([1, 2, 3])
#=> 11
sum_of_cross_terms([1, 2, 3, 4])
#=> 35
我们看到这个计算的计算复杂度是O(arr.size
),
而暴力方法是 O((arr.size)**2
)。后者的一个例子是
def sum_of_cross_terms(arr)
arr.combination(2).sum { |a,b| a*b }
end
关于ruby - #each 循环中的 #reduce 循环不会迭代整个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69951819/