AoC20/lib/day1/day1.ex

74 lines
1.5 KiB
Elixir
Raw Normal View History

2020-12-01 05:14:57 +00:00
defmodule Day1 do
@example_1 """
1721
979
366
299
675
1456
"""
def part1(example \\ false) do
if(example, do: @example_1, else: File.read!("lib/day1/input.txt"))
|> String.trim()
|> String.split("\n")
|> Enum.map(&String.to_integer/1)
|> all_pairs()
|> find_sum_to_2020()
end
def part2(example \\ false) do
if(example, do: @example_1, else: File.read!("lib/day1/input.txt"))
|> String.trim()
|> String.split("\n")
|> Enum.map(&String.to_integer/1)
|> all_triples()
|> find_sum_to_2020()
end
def all_pairs(items) do
items
|> Enum.drop(-1)
|> Enum.with_index()
|> Enum.flat_map(fn {a, a_index} ->
{_, rest} = Enum.split(items, a_index + 1)
Enum.map(rest, fn b ->
{a, b}
end)
end)
end
def all_triples(items) do
items
|> Enum.drop(-1)
|> Enum.with_index()
|> Enum.flat_map(fn {a, a_index} ->
{_, rest} = Enum.split(items, a_index + 1)
rest
|> Enum.drop(-1)
|> Enum.with_index()
|> Enum.flat_map(fn {b, b_index} ->
{_, rest_rest} = Enum.split(rest, b_index + 1)
Enum.map(rest_rest, fn c ->
{a, b, c}
end)
end)
end)
end
def find_sum_to_2020(groups) do
Enum.find_value(groups, fn items ->
list = Tuple.to_list(items)
if Enum.reduce(list, 0, &(&1 + &2)) == 2020 do
Enum.reduce(list, 1, &(&1 * &2))
else
nil
end
end)
end
end