Module: PairWithGivenSum

Defined in:
lib/pair_with_given_sum.rb

Class Method Summary collapse

Class Method Details

.parseArray(arr) ⇒ Object



25
26
27
# File 'lib/pair_with_given_sum.rb', line 25

def PairWithGivenSum.parseArray(arr)
   return arr.scan(/\d+/).map(&:to_i)
end

.run(str, sum) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/pair_with_given_sum.rb', line 2

def PairWithGivenSum.run(str, sum)
  if str.nil?  || str.length <=2 || sum.nil?
    puts "Must be given a string representing an integer array and an integer sum."
  else
     array = PairWithGivenSum.parseArray(str)
     array.sort!
     smallIndex = 0
     largeIndex = array.length - 1
     while largeIndex > smallIndex
       tmpSum = array[largeIndex] + array[smallIndex]
       if tmpSum == sum
         puts "Sum of #{array[smallIndex]} & #{array[largeIndex]} = #{sum}"
         return
       elsif tmpSum > sum
         largeIndex -= 1
       else
         smallIndex += 1
       end
     end
     puts "No pair with sum of #{sum}"
  end
end