Skip to content

Instantly share code, notes, and snippets.

@rbishop
Last active August 29, 2015 14:02
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 rbishop/729a7f68426a01f8cfc4 to your computer and use it in GitHub Desktop.
Save rbishop/729a7f68426a01f8cfc4 to your computer and use it in GitHub Desktop.
Find all the unique pairs of numbers that add to 100 in a list
defmodule UniquePairs do
def hundreds(numbers) do
numbers
|> combinations
|> is_hundred
|> sort_pairs
|> Enum.uniq
end
def combinations(numbers) do
for num1 <- numbers,
num2 <- numbers,
do: [num1, num2]
end
def is_hundred(numbers), do: Enum.filter(numbers, fn (pair) -> Enum.sum(pair) == 100 end)
def sort_pairs(numbers), do: Enum.map(numbers, &Enum.sort/1)
end
sample_data = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]
IO.inspect UniquePairs.hundreds(sample_data)
sample_data = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]
pairs = sample_data.combination(2).to_a
hundreds = pairs.select { |pair| pair[0] + pair[1] == 100 }
hundreds.map! { |pair| pair.sort }
hundreds.uniq!
puts hundreds.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment