Skip to content

Commit 899c42f

Browse files
committed
return first pair whose sum is equal to given number
1 parent 7fa8cea commit 899c42f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

beginners/first_sum_of_pairs.rb

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# return the first pair starting from left whose sum is equal to given number
2+
# sum_pairs([10, 5, 2, 3, 7, 5], 10) => [3,7]
3+
# ^-----------^
4+
# ^--^ #[3,7] came earlier than [5,5]
5+
6+
def sum_pairs(ints, sum)
7+
hash = {}
8+
9+
ints.each_with_index do |i,j|
10+
if hash[i].nil?
11+
hash[i]=[1,[j]]
12+
else
13+
hash[i][0]+=1
14+
hash[i][1]<<j
15+
end
16+
end
17+
# print hash
18+
# puts ""
19+
20+
min=10000000000
21+
tuple=nil
22+
ints.each do |i|
23+
if hash[sum-i].nil? || hash[i].nil?
24+
next
25+
elsif sum-i == i
26+
if hash[i][0]>1 && min>hash[i][1][1]
27+
min = hash[i][1][1]
28+
tuple = [i,i]
29+
hash[i]=nil
30+
end
31+
elsif min>hash[sum-i][1][0]
32+
min = hash[sum-i][1][0]
33+
tuple = [i,sum-i]
34+
hash[i]=nil
35+
hash[sum-i]=nil
36+
else
37+
hash[i]=nil
38+
hash[sum-i]=nil
39+
end
40+
# print "#{min} #{tuple}\n"
41+
end
42+
tuple
43+
end
44+
45+
print sum_pairs([1, 2, 3, 4, 1, 0], 2)
46+
print sum_pairs([1, 2, 3, 4, 2, 5, 7, 6, 7], 9)
47+
print sum_pairs([1, 2, 3, 4, 1, 4, 8, 9, 5], 8)
48+
49+
50+
#
51+
# def sum_pairs(ints, s)
52+
# seen = {}
53+
# for i in ints do
54+
# return [s-i, i] if seen[s-i]
55+
# seen[i] = true
56+
# end
57+
# nil
58+
# end
59+
#

0 commit comments

Comments
 (0)