Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
找到给定数组中任意两个元素之和的好方法是什么?
我有以下代码,但它看起来有点难看
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
xs = [1, 5, 8, 10] xs.combination(2).map { |x, y| x + y } #=> [6, 9, 11, 13, 15, 18]