Day 15 Parts 1 and 2

This commit is contained in:
Adam Millerchip 2020-12-15 15:02:47 +09:00
parent 1318f63b25
commit bbb8ba7251
3 changed files with 74 additions and 1 deletions

View File

@ -2,7 +2,7 @@
My (attempted) solutions to [Advent of Code 2020](https://adventofcode.com/2020) in Elixir.
<img width="978" alt="image" src="https://user-images.githubusercontent.com/498229/102170372-8c706900-3ed7-11eb-8bdd-3b0f28b95fde.png">
<img width="978" alt="image" src="https://user-images.githubusercontent.com/498229/102176995-f132c000-3ee5-11eb-9dc5-7eb450c4d68f.png">
## Strategy

43
day15/README Normal file
View File

@ -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...

30
day15/day15.exs Normal file
View File

@ -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()