Closest Numbers

  • + 0 comments

    using Ruby

      arr.sort!
      min_diff = 10000000
      result = {}
      
      (0..(arr.size - 2)).each do |i|
        diff = (arr[i+1] - arr[i]).abs
        if diff <= min_diff
          min_diff = diff
          result[diff] ||= []
          result[diff] << [arr[i], arr[i+1]]
        end
      end
      result[min_diff]