Created
December 1, 2018 09:58
-
-
Save jemmyw/4e88f50b3842db96dd51dae5f4d7ac17 to your computer and use it in GitHub Desktop.
aoc 1.exs
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 One do | |
def split(str) do | |
[String.slice(str, 0..0), String.to_integer(String.slice(str, 1..-1))] | |
end | |
def value("+", n), do: n | |
def value("-", n), do: -n | |
def split_value(str) do | |
apply(One, :value, split(str)) | |
end | |
end | |
defmodule OneTwo do | |
def next([n | rest], freq, freqs) do | |
nf = freq + One.split_value(n) | |
find(rest ++ [n], nf, [nf | freqs]) | |
end | |
def find(list, freq, []) do | |
next(list, freq, []) | |
end | |
def find(list, freq, freqs) do | |
[_ | old_freqs] = freqs | |
cond do | |
freq in old_freqs -> freq | |
true -> next(list, freq, freqs) | |
end | |
end | |
end | |
{:ok, content} = File.read("1.txt") | |
lines = String.split(content) | |
# Answer 1 | |
IO.puts(Enum.reduce(lines, 0, fn x, acc -> One.split_value(x) + acc end)) | |
# Answer 2 | |
IO.puts(OneTwo.find(lines, 0, [])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment