prabhu - 1 year ago 70
Ruby Question

# Find if n exists as a sum of any 2 numbers in the given array

I am trying to find whether

`n`
exists as a sum of any two numbers in the passed array if so return
`true`
else
`false`
, the problem with my code is that
`inject`
is not iterating as I want it to. What am I doing wrong?

``````def sum_to_n?(array,n)
array.each do |i|
array.inject(i) do |memo,var|
if memo + var == n
return true
else
return false
end
end
end
end

puts sum_to_n?([1,2,3,4,5],9)
``````

Here is an approach :

``````def sum_to_n?(a,n)
!!a.find{|e| a.include?(n-e)}
end
a = [1,2,3,4,5]
sum_to_n?(a,9) # => true
sum_to_n?(a,11) # => false
``````

If you want to get those 2 elements:

``````def sum_to_n?(a,n)
num=a.find{|e| a.include?(n-e)}
unless num
puts "not exist"
else
p [n-num,num]
end
end
a = [1,2,3,4,5]
sum_to_n?(a,9)
# >> [5, 4]
sum_to_n?(a,11)
# >> not exist
``````

Logic

`Enumerable#find` method passing one array element per iteration.Now for any iteration,say I have an element `e`,and I subtracted it from n. Now I was just testing that `(n-e)` is present in the source array.If I found a match `#find` will stop finding,and immediately will return `e`.If not found,then it will go for next iteration. If `#find` completes its iteration,but didn't find `(n-e)`,as per the documentation it will return `nil`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download