AoC18/lib/day1/day1.ex

65 lines
1.3 KiB
Elixir
Raw Normal View History

2018-12-01 18:51:14 +00:00
defmodule Day1 do
def calculate_frequency(shifts) do
shifts
2018-12-03 21:58:13 +00:00
|> Enum.reduce(0, &+/2)
2018-12-01 18:51:14 +00:00
end
def first_repetition(shifts, index \\ 0, sum \\ 0, seen \\ [0]) do
sum = sum + Enum.at(shifts, index)
next_index = rem(index + 1, Enum.count(shifts))
cond do
Enum.member?(seen, sum) ->
sum
2018-12-03 21:58:13 +00:00
2018-12-01 18:51:14 +00:00
true ->
first_repetition(shifts, next_index, sum, [sum | seen])
end
end
2018-12-01 19:11:51 +00:00
def first_repetition_stream(shifts) do
shifts
2018-12-03 21:58:13 +00:00
|> Stream.cycle()
|> Enum.reduce_while({0, [0]}, fn shift, {sum, seen} ->
sum = sum + shift
cond do
Enum.member?(seen, sum) -> {:halt, sum}
true -> {:cont, {sum, [sum | seen]}}
end
end)
2018-12-01 19:11:51 +00:00
end
2018-12-02 16:04:05 +00:00
def first_repetition_mapset(shifts) do
shifts
2018-12-03 21:58:13 +00:00
|> Stream.cycle()
|> Enum.reduce_while({0, MapSet.new([0])}, fn shift, {sum, seen} ->
sum = sum + shift
cond do
sum in seen -> {:halt, sum}
true -> {:cont, {sum, MapSet.put(seen, sum)}}
end
end)
2018-12-02 16:04:05 +00:00
end
2018-12-01 18:51:14 +00:00
def parse_input() do
File.read!("lib/day1/input.txt")
2018-12-03 21:58:13 +00:00
|> String.split("\n")
|> Enum.map(fn s ->
{num, _} = Integer.parse(s)
num
end)
2018-12-01 18:51:14 +00:00
end
def part1() do
parse_input()
2018-12-03 21:58:13 +00:00
|> calculate_frequency()
2018-12-01 18:51:14 +00:00
end
def part2() do
parse_input()
2018-12-03 21:58:13 +00:00
|> first_repetition_mapset()
2018-12-01 18:51:14 +00:00
end
2018-12-03 21:58:13 +00:00
end