1

找到给定数组中任意两个元素之和的好方法是什么?

我有以下代码,但它看起来有点难看

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
4

1 回答 1

1
xs = [1, 5, 8, 10]
xs.combination(2).map { |x, y| x + y }
#=> [6, 9, 11, 13, 15, 18]
于 2013-10-21T06:15:25.603 回答