Encoding Error
defmodule Aoc2020.Day9 do
@moduledoc "Encoding Error"
def run(), do: part_1() |> part_2()
def part_1() do
parse_input()
|> Enum.split(25)
|> (fn {preamble, rest} -> test_preamble_sum(Enum.reverse(preamble), rest) end).()
end
def part_2(invalid_number) do
parse_input()
|> Stream.scan([], &[&1 | &2])
|> Enum.find_value(fn sublist -> sum_continuous(Enum.reverse(sublist), invalid_number) end)
|> Enum.sum()
end
def parse_input() do
File.read!("priv/inputs/2020/day9.txt")
|> String.trim()
|> String.split("\n")
|> Enum.map(fn line -> String.to_integer(line) end)
end
def test_preamble_sum(preamble, [next | rest]) do
if has_pair_sum?(preamble, next) do
test_preamble_sum([next | Enum.take(preamble, 24)], rest)
else
next
end
end
def has_pair_sum?(prev25, next) do
pairs = for x <- prev25, y <- prev25, x != y, do: [x, y]
Enum.find(pairs, fn [x, y] -> x + y == next end)
end
def sum_continuous(lst = [head | rest], target_number) do
sum = Enum.sum(lst)
cond do
sum == target_number ->
Enum.sort(lst) |> (fn [head | rest] -> [head, List.last(rest)] end).()
sum < target_number ->
false
sum > target_number ->
sum_continuous(rest, target_number)
end
end
end