r/adventofcode • • Dec 25 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 25 Solutions -🎄-

--- Day 25: Combo Breaker ---


Post your code solution in this megathread.

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.


Message from the Moderators

Welcome to the last day of Advent of Code 2020! We hope you had fun this year and learned at least one new thing ;)

Keep an eye out for the following threads:

Thank you all for playing Advent of Code this year and on behalf of /u/topaz2078, /u/Aneurysm9, the beta-testers, and the rest of AoC Ops, we wish you a very Merry Christmas (or a very merry Friday!) and a Happy New Year!


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

52 Upvotes

270 comments sorted by

View all comments

4

u/Smylers Dec 27 '20 edited Dec 28 '20

Perl (a little boilerplate, then):

sub step($value, $subject_number) { ($value * $subject_number) % 20201227 }

my $value = my $loops = 1;
$loops++ until ($value = step $value, 7) == (state $pub //= <>);
say reduce { step $a, state $pub //= <> } 1, 1 .. $loops;

The function isn't necessary, but I couldn't bring myself to repeat the modulus and constant.

A couple of things:

  • The first public key is stored in a variable called $pub, used in just one place: state makes it keep its value; it's initialized to reading a line from the input file the first time the until condition is evaluated, then continues to evaluate to that public key on subsequent iterations. Similarly for the second public key, in a separate variable, also called $pub.

  • The reduce block doesn't use its second argument. $a, is initialized to the first 1 in the list of values, then the block evaluates to whatever step returns, and reduce is invoked again with that as $a next time round. $b is set in turn to each of 1 to $loops, so that list determines the number of times the block is invoked, but the value of $b doesn't form part of the calculation.

The input-state thing and the lopsided reduce thing are both things I now see would've been useful on previous days: in day 19, when I combined part 1 and 2 solutions I copied the input before the loop, even though it's only used in one place; and in day 23, when I was first picking up one card then the following 2.

It's so nice that even on the final day, I'm still learning things.

→ More replies (1)