diff --git a/2020/day15/day15.ex b/2020/day15/day15.ex index d0d7a8f..4052258 100644 --- a/2020/day15/day15.ex +++ b/2020/day15/day15.ex @@ -21,7 +21,7 @@ defmodule Day15 do {_, idx} = rest |> 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 end @@ -34,12 +34,55 @@ defmodule Day15 do end end - def part1 do + def part1(limit) do read_input() |> parse_numbers() |> 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 + + 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() |> IO.inspect() +Day15.part1(2020) |> IO.inspect() +Day15.part2(30_000_000) |> IO.inspect()