Watch
1
0
Fork
You've already forked advent-of-code
0

Day 15 Part 2

This commit is contained in:
Jeremy Kaplan 2020-12-14 22:01:17 -08:00
commit cbecec6a40

View file

@ -21,7 +21,7 @@ defmodule Day15 do
{_, idx} = {_, idx} =
rest rest
|> Enum.with_index() |> Enum.with_index()
|> Enum.find({previous, -1}, fn {num, idx} -> num == previous end) |> Enum.find({previous, -1}, fn {num, _idx} -> num == previous end)
idx + 1 idx + 1
end end
@ -34,12 +34,55 @@ defmodule Day15 do
end end
end end
def part1 do def part1(limit) do
read_input() read_input()
|> parse_numbers() |> parse_numbers()
|> Enum.reverse() |> Enum.reverse()
|> run(2020) |> run(limit)
end
defp setup(initial) do
cache =
initial
|> Enum.slice(0..-2)
|> Enum.with_index()
|> Enum.into(%{})
{cache, Enum.at(initial, -1)}
end
defp next2(cache, said, now) do
now - Map.get(cache, said, now)
end
defp run2(cache, said, now, stop) do
say = next2(cache, said, now)
if now + 1 == stop do
said
else
run2(Map.put(cache, said, now), say, now + 1, stop)
end end
end end
Day15.part1() |> IO.inspect() def part2(limit) do
{cache, said} =
read_input()
|> parse_numbers()
|> setup()
run2(cache, said, map_size(cache), limit)
end
def debug(limit) do
10..limit
|> Enum.filter(fn i ->
p1 = part1(i)
p2 = part2(i)
p1 != p2
end)
end
end
Day15.part1(2020) |> IO.inspect()
Day15.part2(30_000_000) |> IO.inspect()