Skip to content

Instantly share code, notes, and snippets.

@aarti
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save aarti/8ca0f144c88f6e053402 to your computer and use it in GitHub Desktop.

Select an option

Save aarti/8ca0f144c88f6e053402 to your computer and use it in GitHub Desktop.
a = [1,2,3,4,5]
n = 5
def match_sum_pairs_naive(a,n)
for i in 0..a.length-2
for j in i+1..a.length-1
return [a[i],a[j]] if a[i]+a[j]==n
end
end
end
p match_sum_pairs_naive(a,n)
def match_sum_pairs_positive(a,n)
h = {}
for i in 0..a.length-1
h[n-i] = i
end
for i in 0..a.length-1
return [a[i],h[a[i]] ]if h[a[i]]
end
end
p match_sum_pairs_positive(a,n)
def match_sum_pairs_sort(a,n)
b = a.sort
i,j = 0,a.length-1
while i<j do
sum = a[i] +a[j]
if sum == n
return [a[i],a[j]]
elsif sum < n
i+=1
else
j-=1
end
end
end
p match_sum_pairs_sort(a,n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment