Last active
August 29, 2015 14:02
-
-
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
This file contains hidden or 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
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) |
This file contains hidden or 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
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