Skip to content

Commit

Permalink
Add day 9
Browse files Browse the repository at this point in the history
  • Loading branch information
LostKobrakai committed Dec 9, 2020
1 parent 586e5ef commit 2734ef2
Show file tree
Hide file tree
Showing 5 changed files with 1,147 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/aoc2020.ex
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,7 @@ defmodule Aoc2020 do

defdelegate day8_part1(), to: Aoc2020.Day8, as: :part1
defdelegate day8_part2(), to: Aoc2020.Day8, as: :part2

defdelegate day9_part1(), to: Aoc2020.Day9, as: :part1
defdelegate day9_part2(), to: Aoc2020.Day9, as: :part2
end
63 changes: 63 additions & 0 deletions lib/aoc2020/day9.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
defmodule Aoc2020.Day9 do
def part1() do
part1(load_input())
end

def part1(input, preamble \\ 25) do
input
|> Stream.chunk_every(preamble + 1, 1)
|> Enum.find_value(fn list ->
{total, options} = List.pop_at(list, -1)

combinations =
for a <- options, b <- options, uniq: true do
[a, b] |> Enum.sort() |> List.to_tuple()
end

valid? = Enum.any?(combinations, fn {a, b} -> a + b == total end)

unless valid?, do: total
end)
end

def part2() do
input = load_input()
part2(input, part1(input))
end

def part2(input, search) do
list =
input
|> Stream.chunk_while([], chunk_fun(search), &after_fun/1)
|> Enum.at(0)

Enum.min(list) + Enum.max(list)
end

defp chunk_fun(total) do
fn element, acc ->
with_element = [element | acc]
check_sum(with_element, total)
end
end

defp check_sum(with_element, total) do
case Enum.sum(with_element) do
^total -> {:cont, with_element, List.delete_at(with_element, -1)}
t when t < total -> {:cont, with_element}
t when t > total -> check_sum(List.delete_at(with_element, -1), total)
end
end

defp after_fun(acc), do: {:cont, acc}

@doc false
def load_input do
path = Application.app_dir(:aoc_2020, "priv/inputs/09/stream.txt")

path
|> File.stream!()
|> Stream.map(&String.trim/1)
|> Stream.map(&String.to_integer/1)
end
end
Loading

0 comments on commit 2734ef2

Please sign in to comment.