diff --git a/README.md b/README.md index 5ab86cc..fbe27f5 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/day13/README b/day13/README index 399ba4d..74d4957 100644 --- a/day13/README +++ b/day13/README @@ -21,6 +21,9 @@ minutes to wait. Take the minimum. $ elixir day13part2.exs *runs forever* +$ elixir day13part2-cheating.exs +741745043105674 + Thoughts: Another one that's impossible to brute force. Currently stuck. @@ -39,6 +42,15 @@ is important. Going to come back to this later with a clear mind. Not sure I'll get it without a hint. Seems like I have a knowledge gap. +** Update 16 Dec - 3 days later ** + +I did lots of reading into the Chinese Remainder Theorem, but wasn't able to work out +how to apply that here. I'm giving in and asking for help. Voltone on Elixir Forum had +the answer, so I adapted it to my program and it outputted the right answer - so I'm +claiming the star :P, although I'm not going to claim I solved this, so I added that +version to day13part2-cheating.exs with credit. Will definitely come back to this to +understand it properly. + +------------------+ | Overall Thoughts | diff --git a/day13/day13part2-cheating.exs b/day13/day13part2-cheating.exs new file mode 100644 index 0000000..7a192fb --- /dev/null +++ b/day13/day13part2-cheating.exs @@ -0,0 +1,36 @@ +defmodule Day13Part2 do + def run do + File.read!("input") + |> String.split(["\n", ","], trim: true) + |> Enum.drop(1) + |> Enum.map(&parse_schedule/1) + |> Enum.with_index() + |> Enum.reject(&match?({:any, _}, &1)) + |> Enum.reduce({0, 1}, &find_sequential_departures/2) + |> elem(0) + |> IO.puts() + end + + def parse_schedule(id) do + case Integer.parse(id) do + {id, ""} -> id + _ -> :any + end + end + + # Adapted from voltone's solution ❤️ + # https://elixirforum.com/t/advent-of-code-2020-day-13/36180/6 + defp find_sequential_departures({bus, index}, {t, step}) do + if rem(t + index, bus) == 0 do + {t, lcm(step, bus)} + else + find_sequential_departures({bus, index}, {t + step, step}) + end + end + + defp lcm(a, b) do + div(a * b, Integer.gcd(a, b)) + end +end + +Day13Part2.run() diff --git a/day13/input b/day13/input new file mode 100644 index 0000000..4a527f3 --- /dev/null +++ b/day13/input @@ -0,0 +1,2 @@ +1002460 +29,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,601,x,x,x,x,x,x,x,23,x,x,x,x,13,x,x,x,17,x,19,x,x,x,x,x,x,x,x,x,x,x,463,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,37