Ruby sums of objects in array equal to zero -


write method finds if array of numbers has pair sums zero. careful of case of zero; there needs 2 zeroes in array make pair sums zero.

below code wrote, know wrong. know @ point adding if there 1 0 in array, still return true. new programming , ruby advice appreciated.

thanks!

    def has_zero?(array)         left, right = [-1,1]         lefter=[]         righter=[]         righter=array.each {|x| x+= array[right]}         lefter=array.each {|x| x+= array[left]}         if lefter.include?(0) || righter.include?(0)             return true         else return false         end         left,right = [left-1,right+1]     end 

ruby has built-in methods make pretty easy:

def has_zero_sum_pair?(a)   a.permutation(2).any?{|pair| pair.inject(:+) == 0} end 

a.permutation(2) gives every pair in a. any? returns true if block ever returns true. inject(:+) easy way sum of array.

has_zero_sum_pair?([1, 2, 3]) # => false  has_zero_sum_pair?([1, 2, 3, -2]) # => true  has_zero_sum_pair?([1, 2, 3, 0]) # => false  has_zero_sum_pair?([0, 1, 2, 3, 0]) # => true 

update: if didn't know array#permutation , had accomplish in first way came mind, or if concerned performance, i'd this:

def has_zero_sum_pair2?(a)   (0..a.length-2).each |i|     (i+1..a.length-1).each |j|       return true if a[i] + a[j] == 0     end   end   false end 

i find uglier , more error-prone, , took longer write. it's 4 times faster small arrays , 10 times faster larger arrays. it's typical in programming have easy way works enough in cases isn't ideal in performance. better performance can attained without costing clarity choosing better algorithm or data structure. trade-off has made.

update 2: if cared performance, i'd use @fmc's technique. that's great example of using better data structure , algorithm huge performance gains.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -