From bbb8ba725125e37f8ada776f88f286887e7c5467 Mon Sep 17 00:00:00 2001 From: Adam Millerchip Date: Tue, 15 Dec 2020 15:02:47 +0900 Subject: [PATCH] Day 15 Parts 1 and 2 --- README.md | 2 +- day15/README | 43 +++++++++++++++++++++++++++++++++++++++++++ day15/day15.exs | 30 ++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 day15/README create mode 100644 day15/day15.exs diff --git a/README.md b/README.md index ec3061a..5ab86cc 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ My (attempted) solutions to [Advent of Code 2020](https://adventofcode.com/2020) in Elixir. -image +image ## Strategy diff --git a/day15/README b/day15/README new file mode 100644 index 0000000..31fa360 --- /dev/null +++ b/day15/README @@ -0,0 +1,43 @@ +Day 15 Notes + ++--------+ +| Part 1 | ++--------+ + +$ elixir day15.exs 2020 +253 + +Thoughts: + +Separate function to set the initial state. +Store the last two round numbers for each answer. +If it's the first time, store the same round number twice, which results in 0 +when subtracted. + + ++--------+ +| Part 2 | ++--------+ + +$ elixir day15.exs 30000000 +13710 + +Thoughts: + +I'm not sure if this was supposed to be brute-forcible. + +I think it is and that I designed the algorithm efficiently in the first part. +The answer is a bit slow, but that's probably due to all the map updates. Using +a more efficient data structure would probably speed it up - guessing this is +faster in mutable languages. + +Anyway, no code changes here, so for this excercise I decided to combine the +two answers, and just specify the last round via the command-line. + + ++------------------+ +| Overall Thoughts | ++------------------+ + +Did this one pretty quickly. May even have time to go back to day 13 and learn +about the Chinese Remainder Theorem... diff --git a/day15/day15.exs b/day15/day15.exs new file mode 100644 index 0000000..3771108 --- /dev/null +++ b/day15/day15.exs @@ -0,0 +1,30 @@ +defmodule Day15Part1 do + @input [18, 8, 0, 5, 4, 1, 20] + + def run do + [stop] = System.argv() + + start(@input, nil, 1, String.to_integer(stop), %{}) + |> IO.puts() + end + + def start([], last, round, stop, state), do: play(last, round, stop, state) + + def start([num | rest], _last, round, stop, state) do + start(rest, num, round + 1, stop, Map.put(state, num, {round, round})) + end + + def play(num, stop, stop, state) do + {a, b} = state[num] + b - a + end + + def play(num, round, stop, state) do + {a, b} = state[num] + say = b - a + state = Map.update(state, say, {round, round}, fn {_a, b} -> {b, round} end) + play(say, round + 1, stop, state) + end +end + +Day15Part1.run()