Created
December 17, 2015 19:02
-
-
Save AntonFagerberg/e4b6360eb247c975f3cb 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
defmodule Day_17 do | |
def solve(input, target) do | |
Regex.scan(~r/-?\d+/, input) | |
|> Enum.map(&hd/1) | |
|> Enum.map(&Integer.parse/1) | |
|> Enum.map(&(elem(&1, 0))) | |
|> process([], target) | |
end | |
defp process([], acc, target) do | |
if Enum.sum(acc) == target, do: 1, else: 0 | |
end | |
defp process([head | tail], acc, target) do | |
process(tail, [head] ++ acc, target) + process(tail, acc, target) | |
end | |
def solve2(input, target) do | |
Regex.scan(~r/-?\d+/, input) | |
|> Enum.map(&hd/1) | |
|> Enum.map(&Integer.parse/1) | |
|> Enum.map(&(elem(&1, 0))) | |
|> process2([], target) | |
|> Enum.reduce({0, -1}, fn (nr, {acc_count, acc_min}) -> | |
cond do | |
acc_min == -1 || nr < acc_min -> {1, nr} | |
nr == acc_min -> {acc_count + 1, acc_min} | |
true -> {acc_count, acc_min} | |
end | |
end) | |
|> elem(0) | |
end | |
defp process2([], acc, target) do | |
if Enum.sum(acc) == target, do: [length(acc)], else: [] | |
end | |
defp process2([head | tail], acc, target) do | |
process2(tail, [head] ++ acc, target) ++ process2(tail, acc, target) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment