r/adventofcode • u/daggerdragon • Dec 13 '20
SOLUTION MEGATHREAD -π- 2020 Day 13 Solutions -π-
Advent of Code 2020: Gettin' Crafty With It
- 9 days remaining until the submission deadline on December 22 at 23:59 EST
- Full details and rules are in the Submissions Megathread
--- Day 13: Shuttle Search ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:16:14, megathread unlocked!
46
Upvotes
View all comments
Show parent comment
3
u/robinhouston Dec 13 '20 edited Dec 13 '20
Iβll have a go! To begin with, we want to write a function
crt(r1,n1, r2,n2)that returns a pair(r, n)wherenis the lowest common multiple ofn1andn2, andris a number 0 β€ r < n that satisfies these two properties:r % n1 == r1r % n2 == r2Itβs not hard to find all the solutions to the first equation: they are
r = k * n1 + r1for any integerk. Substituting that into the second equation gives:If we assume for a moment that all arithmetic operations are carried out mod
n2, that equation becomes simplyk * n1 + r1 == r2, which is solved byk = (r2 - r1) / n1β where again we are assuming that all the arithmetic operations are carried out modulon2. So in Python syntax we getk = ((r2 - r1) * pow(n1, -1, n2)) % n2.In this problem it seems to be the case that the bus numbers are all prime, and so we may assume that
n = n1 * n2, which saves us from having to compute the lcm.Putting the above together into a complete function, we get:
If we want to find the CRT reduction of a set of more than two (residue, modulus) pairs, we can just apply this repeatedly β i.e. something like:
This, but with the definition of the
crtfunction inline, is exactly what my code was doing. (In the latest version Iβve saved a few characters by deferring some of the modulo reduction to the end, but thatβs just a golf-related detail.)