Created
September 23, 2012 23:43
-
-
Save ximus/3773449 to your computer and use it in GitHub Desktop.
Testing max's reasoning
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
# I'm assuming sum operations are cheap and I won't gain much, if at all, from | |
# memoizing sums. | |
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 | |
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,3]] => 4, | |
[6, [3,3,3]] => 9, | |
[6, [1,5]] => 2 | |
} | |
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