-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
586e5ef
commit 2734ef2
Showing
5 changed files
with
1,147 additions
and
0 deletions.
There are no files selected for viewing
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
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
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 |
Oops, something went wrong.