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.
与えられた配列内の任意の 2 つの要素の合計を見つける良い方法は何ですか?
次のコードがありますが、見栄えが悪いです
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]