Number Pairs

配列と数字が与えられたとき、その配列のうち2つの和がその数字となる
組み合わせを求める。


正答率86%

((296.0/(296+48))*100).round

設問

You are given a sorted array of positive integers and a number 'X'. Print out all pairs of numbers whose sum is equal to X. Print out only unique pairs and the pairs should be in ascending order

Input sample:

Your program should accept as its first argument a filename. This file will contain a comma separated list of sorted numbers and then the sum 'X', separated by semicolon. Ignore all empty lines. If no pair exists, print the string NULL eg.

1,2,3,4,6;5
2,4,5,6,9,11,15;20
1,2,3,4;50

Output sample:

Print out the pairs of numbers that equal to the sum X. The pairs should themselves be printed in sorted order i.e the first number of each pair should be in ascending order .e.g.

1,4;2,3
5,15;9,11
NULL

やってみた

#!/usr/bin/env ruby

def pairs(ar, n)
  pairs = ar.split(',').map(&:to_i).combination(2).select do |com|
    com.inject(:+) == n.to_i
  end
end

def format(pairs)
  pairs.size.zero?? 'NULL' : pairs.map{ |pair| pair.join(',') }.join(';')
end

ARGF.lines do |line|
  line.chomp.split(';').instance_eval do |ar, n|
    puts format(pairs(ar, n))
  end
end