Skip to content

Instantly share code, notes, and snippets.

@compwron
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save compwron/115a7cf9aaa9d5271e2a to your computer and use it in GitHub Desktop.
Save compwron/115a7cf9aaa9d5271e2a to your computer and use it in GitHub Desktop.
sum2 in n*2
def sum2 choices, result
arrays = []
choices.each_with_index {|i, index|
choices.each_with_index {|j, index2|
break if index == index2
arrays << [i, j] if i + j == result
}
}
arrays
end
def sum2 choices, result
complements = choices.inject({}) { |agg, choice|
agg[result - choice] = choice unless agg.keys.include?(choice)
agg
}
choices.map { |choice|
if !complements[choice].nil?
[choice, complements[choice]]
end
}.compact
end
# p sum2 [4, 5, 7, 6, 2, 1], 3 # [[1, 2]]
# p sum2 [-1, 0, 1, 2], 1 # [[1, 0], [2, -1]]
p sum2 [-1, 0, 1, 2], 0 # [[1, 0], [2, -1]]
big = 10
# p sum2((-big..big), 0)
@compwron
Copy link
Author

def sum2 choices, result
complements = choices.inject({}) { |agg, choice|
agg[result - choice] = choice unless agg.keys.include?(choice)
agg
}

choices.map { |choice|
if !complements[choice].nil?
[choice, complements[choice]]
end
}.compact
end

p sum2 [4, 5, 7, 6, 2, 1], 3 # [[1, 2]]

p sum2 [-1, 0, 1, 2], 1 # [[1, 0], [2, -1]]

p sum2 [-1, 0, 1, 2], 0 # [[1, 0], [2, -1]]

big = 10

p sum2((-big..big), 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment