This commit is contained in:
Shadowfacts 2020-12-13 12:46:31 -05:00
parent ab1e845162
commit ec84c5870b
2 changed files with 69 additions and 0 deletions

67
lib/day13/day13.ex Normal file
View File

@ -0,0 +1,67 @@
defmodule Day13 do
@example """
939
7,13,x,x,59,x,31,19
"""
def part1(example \\ false) do
{earliest_time, busses} = parse_input(example)
bus_id =
busses
|> Enum.reject(&(&1 == "x"))
|> Enum.min_by(fn bus ->
bus - rem(earliest_time, bus)
end)
bus_id * (bus_id - rem(earliest_time, bus_id))
end
def part2(example \\ false) do
{_, busses} = parse_input(example)
busses =
busses
|> Enum.with_index()
|> Enum.reject(&(elem(&1, 0) == "x"))
find_time(0, busses)
end
def parse_input(example) do
[l1, l2] =
if(example, do: @example, else: File.read!("lib/day13/input.txt"))
|> String.trim()
|> String.split()
busses =
l2
|> String.split(",")
|> Enum.map(fn
"x" -> "x"
s -> String.to_integer(s)
end)
{String.to_integer(l1), busses}
end
def find_time(time, busses) do
{valid, rest} =
Enum.split_while(busses, fn {id, index} ->
rem(time + index, id) == 0
end)
case rest do
[] ->
time
_ ->
if valid == [] do
raise "uh oh"
end
step = Enum.reduce(valid, 1, &(elem(&1, 0) * &2))
find_time(time + step, busses)
end
end
end

2
lib/day13/input.txt Normal file
View File

@ -0,0 +1,2 @@
1002618
19,x,x,x,x,x,x,x,x,41,x,x,x,37,x,x,x,x,x,367,x,x,x,x,x,x,x,x,x,x,x,x,13,x,x,x,17,x,x,x,x,x,x,x,x,x,x,x,29,x,373,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,23