找到给定数组中任意两个元素之和的好方法是什么?
我有以下代码,但它看起来很丑陋
def sum_to_n?(a, n)
sums = []
a.each_index do |i|
b = a.drop(i+1)
b.each_index do |j|
sums << a[i] + b[j]
end
end
end
答案 0 :(得分:1)
xs = [1, 5, 8, 10]
xs.combination(2).map { |x, y| x + y }
#=> [6, 9, 11, 13, 15, 18]