Created
September 25, 2012 02:44
-
-
Save ximus/3779687 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def complementary_pairs(k, a) | |
matches = 0 | |
a.each_index do |i| | |
# sum the tail, the elements from i (excluded) to the end of a | |
(i...a.length).each do |j| | |
sum = a[i] + a[j] | |
# we have a match but, ... | |
if sum == k | |
# if its the sum of itself, then there can only be one match | |
if i == j | |
matches += 1 | |
# if it is not, then account for the inverse of that pair | |
else | |
matches += 2 | |
end | |
end | |
end | |
end | |
matches | |
end | |
def complementary_pairs(k, a) | |
a.sort! | |
puts "A: #{a.inspect}" | |
matches = 0 | |
left = 0 | |
right = a.length - 1 | |
# lets hand over obvious fails quickly | |
if k < (a.first * 2) or k > (a.last * 2) | |
return 0 | |
end | |
# also if k = 2Umax or 2Umin, then return 2 | |
begin | |
puts "Doing: #{a[left]} + #{a[right]} = #{a[left] + a[right]}" | |
puts "Left: #{left} Right: #{right}" | |
o = matches | |
case a[left] + a[right] <=> k | |
when -1 | |
left += 1 | |
when 0 | |
matches += 2 | |
matches += 1 if left < right && (a[left] == a[right-1] || a[left+1] == a[right]) | |
left += 1 | |
when 1 | |
right -= 1 | |
end | |
puts "Took: #{matches - o}" | |
puts "~~~~~~~~~~~~~~~~~~~~~" | |
end until left == right | |
matches | |
end | |
tests = { | |
[6, [1,8,-3,0,1,3,-2,4,5]] => 7, # textbook case | |
[6, [0]] => 0, | |
[6, [0,0]] => 0, # better test too many cases than not enough... | |
[6, [3]] => 2, | |
[6, [3,3]] => 6, | |
[6, [3,3,3]] => 16, | |
[6, [1,5]] => 2, | |
[6, [6]] => 0 | |
} | |
tests.each do |args, expected| | |
got = complementary_pairs(*args) | |
unless got == expected | |
raise "expected #{expected}, not #{got} from complementary_pairs(#{args.inspect})" | |
end | |
end | |
puts "All Green" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment