r/adventofcode • u/daggerdragon • Dec 21 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 21 Solutions -🎄-
Advent of Code 2021: Adventure Time!
- 2 days left to submit your adventures!
- Full details and rules are in the submissions megathread: 🎄 AoC 2021 🎄 [Adventure Time!]
--- Day 21: Dirac Dice ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Format your code appropriately! How do I format code?
- 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:20:44, megathread unlocked!
49
Upvotes
14
u/StripedSunlight Dec 21 '21 edited Dec 21 '21
Python3
Github
Runs in <3 miliseconds, no caching, no recursion, no special language tricks, I just worked out the math/algorithm to do it properly (plus some entirely unnecessary OOP) Edit: I ran it on
WINNING_SCORE=200to see how long it would take: <0.5 seconds!Edit to add explanation of what algorithm actually does.
In short, I worked out that what rounds each player reaches 21 points at can be simulated entirely independently, so I have each player play a game by themselves and create a mapping of the round to the number of games that were won on that round - this can be done without simulating every single round by grouping them together, similar to days 6 or 14.
Then it's just a matter of working out how many games were actually won on a round for a given player. This can be determined by calculating how many rounds your opponent hasn't won yet, and multiplying that by the number of games the player won in their own round. Sum that across rounds and you get the total number of games won in the universe.
I generated
POSITION_AND_NUM_MOVES_TO_SCOREandMOVES_COUNTSin a python shell and copy-pasted the output into constants for faster lookup/reference5
u/CCC_037 Dec 21 '21
Rockstar
Part 1:
https://pastebin.com/cuuixRHC
Part 2:
https://pastebin.com/CsJECVNV
Been working further on 19 Dec. My code on that one is a long, long way from 'pretty' but I should have Part 2 done by tomorrow.
3
u/aimor_ Dec 21 '21 edited Dec 21 '21
MATLAB
Another fun day. For Part 2 I just stored a count of how many potential games were in each state (player positions and scores) and accumulated winning games after each turn. Thing I'm most proud of is figuring out how to toggle a number between 1 and 2 :) Also, avoiding
modsince it's such a pain with root 1 counting.3
u/skarlso Dec 21 '21 edited Dec 21 '21
Go / Golang
Lots of reading went into this one. I tried my hand on dynamic programming today for the first time ever. Here are my sources of reading:
Wikipedia
Algorithms by Jeff Erickson
Competitive Programming handbook
Grokking Algorithms
Reading produced this part of the dynamic code:
Full code is here: Github
Not gonna lie. Still not a 100% sure how I made this work. :D
I knew you shouldn't be actually spinning up this many games. The number was a clear indicator of that. It was way too big. I also knew that I should be able to brute force it with memoization. And since there is recursion and memoization involved, I thought this might be a good candidate for DP. And it was. :O
3
u/Falcon_dev Dec 21 '21 edited Dec 22 '21
Straight forward (=not optimized) C# solution that takes ~10 seconds to run.https://github.com/christianfalck/adventchallenge/blob/main/AdventOfCode/Day21.cs
If you look at it and find something that can be done better, I'd like to know - using this challenge to dust off programming after years afk.
Found a potential solution on paper, which would result in what I thought was far less possibilities than the ~3^50 potential different ways if I would recursively calculate all outcomes after each dice throw. Wanted to use the fact that there is only 7 different outcomes with different probability (1,3,6,7,6,3,1) and thought I'd be able to optimize by just counting how many of the opponents moves that didn't result in victory.After giving up and going for the solution above (which I think is 7^x instead of 27^x), I realized that my "optimization" would probably just be 7*7 times faster.After finishing, I saw some solutions where a hash is being used. If anyone have read this far and knows why I'd be grateful; I thought all states were unique.
2
u/marshalofthemark Dec 21 '21 edited Dec 21 '21
Ruby 520/670
Paste
Pretty straightforward day. With only 27 possible universes per roll, it made sense to hard-code a Hash with the possible outcomes without writing loops for "roll each die as 1, 2, or 3".
I'm surprised that, unlike the clownfish day, you could still run Part 2 in a reasonable amount of time (~30s) without memoization. With memoization, it runs in 270ms, and even if you set the winning score to 50, it will spit out a 35-digit number for how many universes Player 1 wins in within 5 seconds.
2
u/jjstatman Dec 21 '21 edited Dec 21 '21
Python 3 3804/3005
Was pretty proud of the solution, runs in under 10 ms on my laptop - I actually haven't seen any other solution with this approach. Basically you count the ways that the game can end in any number of turns, and then count the universes after you have that distribution
2
u/p__m__n Dec 21 '21
Python part2:
Super fast, no recursion. Positions are considered as 0..9 instead of 1..10 for convenience. Could use less lines though.
2
u/xiomatic9999 Dec 21 '21 edited Dec 21 '21
In rust...
This was a fun one, after sleeping on it. With no effort to optimize for performance, runs in <100µs on my i7-1165G7 laptop.
2
u/MarcoServetto Dec 21 '21
I'm solving the advent of code in 42 This is particularly relevant for Day 21 since 42 offers automatic correct by construction caching.
Last post got removed since it only had the link to the video, so here you have it also with the code: code on paste
Code on Dev to Code
Here the video too video
Fell free to contact me if you to know more about the language.
2
u/thibaultj Dec 21 '21
Python 3. (part 2 only) Nothing new here. Use recursion to generate all possible outcomes, and add a nice little cache because of the huge overapping branches.
29
u/jonathan_paulson Dec 21 '21
18/1 :) Python. Video of me solving.
Cool to see a dynamic programming problem!
25
u/4HbQ Dec 21 '21 edited Dec 21 '21
Python, simple recursive solution for both part 2. Runs in 40ms thanks to functools.cache.
The code should be pretty straightforward, but feel free to ask for clarifications.
11
u/autid Dec 21 '21 edited Dec 21 '21
FORTRAN
Part 1 fairly naive approach. Part 2 recursively goes through possible games with a couple of speedups.
Firstly, dice combinations can be aggregated into totals for the three rolls (/3,4,5,6,7,8,9/), and the wins from those multiplied by the number of ways to make them from three rolls (/1,3,6,7,6,3,1/). This cuts down the number of games considered significantly.
Secondly, I cache numbers of wins from each state of (active player, player1 position, player2 position, player1 score, player2 score).
Obviously more optimization that could be done but those are enough to get me down to ~15ms runtime on my laptop.
Finished 846th for part2. Very happy to get my first top 1000 of the year.
9
u/akanet Dec 21 '21
Ruby, 300 something / #40
This one has a really straightforward expression in Ruby and I was pleased to hit on the part 2 solution very quickly! My best time this year. Ruby's array#product + a simply DFS formulation with a good base case and memoization makes this one an execution of a classic genre of CS exercises.
8
u/leijurv Dec 21 '21 edited Dec 21 '21
Python, 25th place, 37th place
Screen recording https://youtu.be/DO84lH11Wbo
Part 1
Part 2
Edit: Part 2 but a bit cuter (more refined) edit 2 part 2 except recursive edit 3 except even cuter with no turns
I used the "lanternfish approach" again for Part 2, in counting how many states exist as a map from state to count. The states are (player 1 score, player 1 position, player 2 score, player 2 position). Then, each multiverse split can be simulated, and the counts multiplied: the new universe's count for the new state is incremented by the old state, multiplied by the number of dice universes for the first player, multiplied by the number of dice universes for the second player. Succinctly:
nuv[(s1, p1, s2, p2)] += cnt * dcount * d2countVery fun problem! I lost a few minutes on part 2 simply forgetting how the game is played, which is that your score comes from your new position, not just the dice roll. I had JUST written it for part 1, but sometimes my mind plays tricks on me :)
7
u/Mrgglock Dec 21 '21
C
GNU C11 / Technically runnable in C++. Managed to get rank #428, kinda cool I guess.
Part 1
Part 2
Both parts are sufficiently different that my code looks vastly different.
I'd say this is more on the readable and understandable end of code in C. So feel free to take a look :)
The idea for part 1 is simple: just implementation; brute force.
The idea for part 2 is a little trickier but doable. The idea is that you can draw a tree graph essentially, and the moment a player wins, the number of universes that player won in is simply the product of all edges from the root to that node. The weight of the edges is given by the probability distribution function of rolling 3 D3s.
0.022s / 1.000s
7
u/SuperSmurfen Dec 21 '21 edited Dec 21 '21
Rust (394/223)
Link to full solution
Really happy with my performance today! Was wondering when a proper dynamic programming question would come up! There is probably some nice bottom-up approach, however, I solved it using memoization with a HashMap as a cache, which I find is always much easier to implement in the moment.
Kind of messy keeping track of both positions, both scores, and who's turn it is. By flipping the scores and positions each call you can avoid a lot of that complexity and simulate it as if it's player 1:s turn every time.
Managed to get it down to about
4mson my machine by pre-computing the possible dice.7
u/Sykout09 Dec 21 '21 edited Dec 21 '21
Rust:
Part 1 didn't have much of an opportunity for optimization, even the naive solution is pretty fast.
The main time saver for both Part 1 and Part 2 is to identify how to process all three die rolls per turn into a single step:
1 + 2 + 3 = 6move,4 + 5 + 6 = 15 = 5move,7 + 8 + 9 = 24 = 4moves,0 + 1 + 2 = 3moves. Notice that every succession, the die effective rolled value just keeps deceasing by 1. We can use this pattern to simplified the overall turn process.With those attempt, you can solve both part 1 and 2 in a fairly quick time.
For Part 2, we can do much better.
First observation is that player 1 and player 2 does not interact, as now the die is not determinate, but fully probabilistic. So, it is actually possible to calculate every turn for player 1 and 2 separately.
Second observation is that the game must end in a finite number of turns. This is due to every turn, a player is guaranteed to increase their score. We can also observe a particular case where the player traverse from
2, +9 => 1, +3 => 4, +9 => 2 ...averaging 2 points minimum per turn. Because of this, it means for a21point game, we can expect it to last at most 11 turns.With that, what we can do for Part 2 is to calculate how many win/lost condition for each player separately, and then combine them for the total win/lost
What we do is that at turn
N, we figure out how many path for player 1 to win on that specific turn, and how many time player 2 reached turnN - 1, but not win. We can then multiply those two number to get number of winning path for player 1 on turn N. Similarly, we do with for player 2, but use winning paths of player 2 on turnN, and player 1 not winning paths on turnN(this is due to player 2 take their turn after player 1). We then sum up all possible steps (which we know is finite) and we get the total wins for both players.As to calculate the win/lost path count, we just recursively simulate each step for both players, just like the naive method. The reason this is faster is a lot faster that we cut the recursion steps in half, as we can now compute both player 1 + 2's turns separately. Compared with my naive solution, it is around 3000 times faster
Bench:
Code for Part 1 + 2
6
u/GrossGrass Dec 21 '21 edited Dec 21 '21
Python
Memoized recursion to the rescue for part 2! Used
functools.cacheto make it easier. Started out with just using(position_1, score_1, position_2, score_2)as parameters but wanted it to be a little cleaner, so I modified myPlayerclass from part 1 to be an immutable data structure that returns a newPlayerinstance on each move.Used a dict to map players by their number and also used
collections.Counterto make updating win counts easy, and kept the logic pretty generalized.For part 1, turns out
itertools.cycleis pretty useful for generating die values here.6
u/tumdum Dec 21 '21 edited Dec 21 '21
my rust solution:
Part 1 is just a straight encoding of the task description. Part 2 uses automatic function memoization provided by the external crate.
edit
Well, it turns out you can improve memoization by hiding the fact which player is the current one. This brings down the runtime to
~15ms.6
u/Smylers Dec 21 '21 edited Dec 22 '21
Vim keystrokes are back! Load your input file, and type this:
Your part 1 answer should be right there, in your editor.
Go on — give it a go! It isn't that much to type, and the
:redr|sl4min the loop makes it fun to watch the numbers whizz by.It uses a few tricks:
2. Each iteration it's added on 3 times (@0⟨Ctrl+A⟩..), because2+2+2=1+2+3.Any questions?
Edit: I woke up this morning and immediately realized my initial solution would fail for anybody's input where the losing player finishes on position
10. AnXhas been inserted to fix that. I've also tweaked the mod-10 calculation to require fewer keystrokes.5
u/Heleor Dec 21 '21
Javascript, 484/412
https://github.com/Heleor/aoc-2020/blob/master/2021/sol21.js
This was a really fun one. I spent some time stuck because I thought the games were independent of each other.
5
u/s-prnv Dec 21 '21 edited Dec 21 '21
Python 180/122, decided to use the probability distribution of three dice rolls to cut down a bit, glad for an easy problem today! Part 2 code below:
5
u/_Unnoteworthy_ Dec 21 '21
Java
Bottom-up dynamic programming (part 2): https://pastebin.com/rNinEr2S
5
u/sim642 Dec 21 '21 edited Dec 21 '21
My Scala solution.
In part 2 I don't simulate all rolls (and their universe splits) individually because it gives unnecessarily many combinations (e.g. 112, 121 and 211 all give the same move). So instead I just precompute the mapping from sum of those three rolls of d3 and how many combinations give that sum. Then I perform recursion, which returns win counts for both players and use the precomputed mapping to take their weighted sum.
Initially this ran part 2 in ~10s. After caching the recursive computations, it's less than 100ms.
5
u/4HbQ Dec 21 '21 edited Dec 21 '21
Python, part 1 golfed to 94 bytes:
Part 2 golfed to 175 bytes. Stores the two scores as a single complex number for convenient summation and multiplication:
5
u/Ximsa4045 Dec 21 '21
C99
Brute force c solution for part 2, takes around 300ms to complete on a r5 2600. Did i mention the 42 loc?
5
u/nibarius Dec 21 '21
Kotlin
My solution seems to be a bit different compared to others so I thought I post it. Like many others I kept a map of how many different dice combinations the different rolls from 3 to 9 have.
When I had this my first step was to recursively calculate the number of ways player 1 could reach the target score in 4 turns, 5 turns, and so on for all number of turns required to reach the target score.
The next step was to recursively calculate the number of ways player 2 could play x number of turns and not reach the target score.
Then it was just a matter of summing up "player 1 finish in x turns" * "player 2 does not finish in x-1 turns" for all x to get how often player 1 wins.
Player one won most of the times for me so that gave me the answer, so I was happy with only checking number of player 1 wins. But it wouldn't have been too difficult to do the same again for player 2 as well.
Part 2 took around 24ms for me so it seems to have been a pretty efficient solution.
5
u/troelsbjerre Dec 21 '21 edited Dec 21 '21
Python
Complex numbers were clearly necessary for this... or something:
Btw, don't ever write code like this. Do as I say; not as I do.
5
u/ai_prof Dec 22 '21 edited Dec 22 '21
Python 3. Part 2 in seven lines of lovely recursion :).
Taking inspiration from thibaultj (thanks!) I created part 2 with a lovely recursive function. There are quicker ways, but more beautiful ones???
Whole part 2 code, with a comment or two...
First rf is (roll,frequency) for the 27 possible rolls:
wins(p1,t1,p2,t2) returns (w1,w2) where wj is the number of wins for player j if player 1 is about to move from the given position. I subtract from 21 (so that you can call wins with different end numbers).
Then we need to call:
Whole code here. Happy recursemass!
4
u/kroppeb Dec 21 '21
Kotlin, 35/53
One of the few days I score worse on part 2 than part 1. Had some doubt that my part 1 was even right when I saw the answer cause p2 had exactly 900 points which felt wrong.
For part 2, I created a map from the state to the amount times it happens. After which I realised I had to use it a a queue, so as a result I have this cursed code =)
4
u/captainAwesomePants Dec 21 '21
Python (paste) (~375)
Fun question. Got the trick of it pretty quickly, might've done better if I remembered that each DIE was a universe and not each ROLL. After that, it was just bugs in my logic leftover from part 1 (I assumed p1 would go and then p2 would go, but really I needed to track whose turn it was as part of the game state).
I feel like storing the game state in a tuple like this is a sin, but I couldn't recall offhand the right way to create a tiny Python class/struct that hashed correctly.
4
u/cmatei Dec 21 '21 edited Dec 21 '21
Recursion with memoization for part2, 70ms. edit: ... and now I realize part2 doesn't actually need the number of dice rolls.
Common Lisp
edit 2: optimized part 2, 14 ms. Deduplication of dice rolls, remove player turn from the cache - from this thread.
4
u/flwyd Dec 21 '21 edited Dec 21 '21
Raku 3364/1406. Memoization cached 22828 trees, saving 135153328222302 wins for part 2, so it ran in less than half a minute, which is a big improvement over the last two days.
My only problems today were comprehending the problem details and correctly implementing the problem details. Once I understood the details of the problem statement, all bugs were pretty easy to spot (like forgetting to increment the turn counter, only rolling the Dirac Dice once, then twice rather than three times… or typing
10instead of100). I didn't encounter any weird behaviors in Raku this time, except the Vim syntax plugin decided that my<(less than) was the start of a multi-line<>string extending from half way through mypart1function into thepart2function.Less parsing, my part 2 solution is:
4
u/SCBbestof Dec 21 '21
Python 3 optimized.
0.15s total time
Any suggestions to make it faster are welcomed XD
4
u/Rangsk Dec 21 '21 edited Dec 21 '21
Rust
1241 / 1010
Full Source
I didn't use dynamic programming / memoization for part 2. Instead, I realized there were only 7 possible sum rolls for 3d3: 3 through 9, and the distribution is well known:
1, 3, 6, 7, 6, 3, 1. Thus, for each step, I create 7 new "universes" and each universe actually counts as that many times more universes all at once. This is slower than memoization would have been, but it still only took ~300ms to run.4
u/ephemient Dec 21 '21 edited Apr 24 '24
This space intentionally left blank.
4
u/spookywooky_FE Dec 21 '21
Since there are so much scrambled codes, here is an organized looking one using c++
4
u/mebeim Dec 21 '21 edited Dec 29 '21
1871/1531 - Python 3 solution - Walkthrough
Cool problem, though the second part gave me a hard time, I somehow forgot that for both d6p2 and d14p2 we basically had to do the same thing! Wow. My original solution was iterative using a
dictas map to remember all the already seen states of the game and their count (with a state being a tuple(score1, score2, pos1, pos2, turn_of_who)). The recursive solution using memoization is much cleaner though, and is what I've implemented after cleaning up part 1's code, and also described in my walkthrough.4
u/vulpine-linguist Dec 21 '21
Pointfree Haskell
some might say "pointless". along the same lines as the others i've seen, part one was just played through, while part two kept track of state/count pairs. but it was fun trying to piece things together in such a way that all the functions could be written without naming their parameters!
4
u/mykdavies Dec 21 '21 edited Jun 29 '23
!> hpf3jyz
API FAILURE
4
u/Mats56 Dec 21 '21
Kotlin
Calculate the frequencies of the various dice rolls
Then recursively search the future. Full code.
No cache, but ran in like 5 seconds so no problem.
4
u/Derp_Derps Dec 21 '21
Python
Vanilla Python, less than 500 bytes. Runs in <100ms.
Part 1 was simple.
while max(S)<1000runs until one of the both scores reaches 1000. Modulo is only needed for the score value, the pawn position increases forever. The same works for the dice value. A dice value of101has the same effect on the score as a value of1.Part 2 is done by iteratively expanding the tuples of
(position,score,count)with theMarray. So, the starting tuple (for8)(8,0,1)expands to:[(11,1,1), (12,2,3), (13,3,6), ... (17,7,1)]. In each loop iteration, the expanding is done for all tuples. After each iteration, I multiply the number of "winnings" for player 1 with the number of "not-winnings" for player 2 and add that value to the total winnings for player 1. Then, I remove all winnings (score > 20) from the list of tuples. This repeats until there are no tuples left.4
u/westacular Dec 21 '21
Swift, part 2 only
Runs in just 0.4 milliseconds for a release build
The possibility of using a recursive / dynamic programming approach for this didn't even occur to me.
Instead, my solution (like some others' here) iterates through the turns, keeping track of the number of possibilities for different not-yet-winning (position, score) states reachable by each player for that turn, while accumulating the total number of possibilities for each player winning.
Since the players don't directly interact in the game, the possibilities for each player can be tracked separately, and multiplied as
total number of possibilities of player A winning on turn N = (number of possibilities of player A reaching score 21 on turn N) * (number of possibilities where player B has not reached score 21 by turn N)
Iteration stops when there are zero possible universes in which one of the players has not yet reached 21.
4
u/goeyj Dec 21 '21 edited Feb 27 '26
[JavaScript]
I seem to have trouble reading, and totally missed the fact that part 2 only asked for the score to go to 21... spent more time than I'd like to admit trying to get something to work for a target score of 1000.
For the recursive calls, I found that you could test all combinations of 3 die rolls and just batch those instead of simulating for each die roll. Basically, if I can get to a space on the board in 6 different ways with some combination of 3 die rolls, I just take the result of that new position * 6.
4
u/SwampThingTom Dec 21 '21
Python
I optimized computing the sums for part 1 which in hindsight was unnecessary, smh.
For part 2, I spent a bit longer than I feel I should have getting the recursion right. Took a look at one of the help threads that made it clear how to do it.
Also this was the first time I've used `functools` to memoize function results. Very cool and easy!
4
u/i_have_no_biscuits Dec 21 '21 edited Dec 21 '21
Python 3 - Part 2 only, non-recursive.
After a couple of rounds of hacking down my state space from 5D to 4D to 2D, this now finishes pretty much instantly. I did originally think about using recursion but trying to work out how to move backwards in time made my brain hurt, so this just keeps going until there are no universes where someone hasn't won.
The inputs are pos1, player 1's initial position, and pos2, player 2's initial position.
4
u/Smylers Dec 21 '21
Perl for part 2 just requires a single line for reading the input, one expression for the base case, and another (albeit more complicated) single expression for the recursive case — this (except for some boilerplate to enable modern syntax and load some library functions) is my entire program :
I say “just”: compared to many days' solutions, it's ended up with (far) fewer lines of code, but took (far) longer to write.
wins()takes the position and target (initially 21) of the player about to move, and the same for the other player (the one who, except at the start, has just moved).If the other player's target has been reached, then the move they just made has won them the game. Return
(0, 1)to indicate this (zero wins for the current player, one win for t'other player).Otherwise, the current player is going to roll the quantum dice. Reading the expression from right to left (ish):
variations_with_repetitionreturns all 29 possible sets of 3 dice rolls, andsumdoes the obvious thing with each set.count_bypopulates a hash for each total, with how many times it occurs among the sets of rolls (just 1 way of adding to 3, but, for instance, 6 different sets of rolls which add up to 5).statevariable to populate it once then keep its value in future invocations of this function. (Actually the variable never even gets used by name; its value is only needed in the place where it's defined, but Perl syntax requires that it have a name.)pairmap. For each pair, it aliases the first value (the total rolled in our case) to$aand the second (the count) to$b.pairmapiteration, calculate the current player's new position based on$a, then recursively invokewins(), swapping the players over (so what's currently the other player will get to roll next time), moving the current player to their new position, and reducing their target by their score from this roll (also their new position). If that move has taken them to their target, then it'll be zero or less and caught by the base case in the nested call; and if it hasn't, the other player gets a go, and so on.$b. There's a pair of win counts — one for each player — so usemapto multiply them both.pairmapiteration, stick each pair of win counts in an array-ref. So the overall output frompairmapwill be a list of those 2-element array-refs, each representing the number of wins for each player for a particular total of the current player's set of dice rolls.zip_by, which invokes its block with the first element from each of the separate arrays, then with the second. Each timesumdoes the obvious thing, meaning we have a single 2-element list giving total number of wins for each player after all the possible dice rolls for the current player.reversethe order of that list of scores to match — the current player will be the other player at the next level of nesting, and so on. (More concretely, when the current player makes a winning roll, the nested function's base case returns(0, 1). We now flip that to(1, 0), to indicate that, at this level, its the current player who won.Note there's nothing in there specifically labelling which player is which, because there's no need to: they swap round at each level, but they always swap back again, so at the outer level we get player 1's number of wins first. (Not that even that matters, when we just want the biggest number of wins.)
:Memoizethe function, so all that recursion has a chance of completing in reasonable time (under ¼ second for my input).Full code, with the function imports.
4
u/TiagoPaolini Dec 22 '21 edited Dec 22 '21
Python 3
Part 1 is very straightforward. Perhaps the one pitfall one may get into is that the position is numbered from 1, instead of 0. So in order to cycle back to the beginning is necessary to subtract 1 from the position before doing the modulo, and then adding 1 to the result.
For the part 1's dice, I made an infinite generator that keeps repeating integers from 1 to 100 infinitely. Then I pulled 3 values at a time from it. The rest was trivial: move the player, calculate the score, alternate between players until someone reaches 1000 points.
Part 2, on the other hand, was more much complicated. I noticed beforehand that it was unfeasible to simulate every last of the trillions of possibilities, that it was necessary to keep track of the win counters in some other form. But I could not figure out initially how to do it. I looked this thread for ideas, and managed to understand the strategy. Credits go to u/SwampThingTom for the idea (this comment, and the code behind it). After understanding the approach, I implemented it on my code (instead of copy/pasting).
The function that calculates the outcome of the games is deterministic. That is, for the same initial conditions the win counts will be the same. So the results can be cached, and returned when the function is called again with the same parameters (saving a lot of processing time).
On the top of that, what matters in each turn is the sum of the 3 rolls, not the value of each dice. So first we pre-calculate all possible combinations of 3 dices, and then count how many times a specific sum appears. Then each sum only needs to be checked once, and then the outcome is multiplied by the number of times that the sum appears. This saves even more processing time.
All in all, what I did for part 2 (using recursion):
Then the function returns 1 for who won and 0 for who lost. This value is multiplied by the number of times that the sum appears, and added to the win counts of the function. The function returns those counters for their callers, after all sums have been iterated. So the win counts are propagated all the way to the original function call, which returns the aggregate win counts of all possible game combinations.
This code took 0.16 seconds to run on my computer. This time was surprisingly low for me, considering that literally trillions of games were accounted precisely. It was fast because of the results caching (or memoization, if you want the technical term) and aggregating the sums together.
My code: Parts 1 and 2
1
u/MarcoServetto Dec 21 '21 edited Dec 21 '21
I'm solving the advent of code in 42 42 supports AUTOMATIC CACHING that is correct by construction. Thus, the day of today was trivial in 42!! I've done a 5min video explanation for it Day 21
Here you can see the code too: Code on paste paste
Code on Dev to Code
Fell free to contact me if you to know more about the language.
1
u/RJdaMoD Dec 21 '21 edited Dec 22 '21
Mathematica
Not so fast today. Part 1 got quite nested and hacky since i unfortunately decided to always give both players a turn and track back who won:
Part 2 hit me quite hard, and it took some time to recover and construct a statistical solution after several drawbacks:
Not the fastest, but it supports an arbitrary number of players (ok, do not try more than 3, and for 3 make yourself comfortable).
1
u/BOT-Brad Dec 21 '21
Golang
Todays puzzle was a fun one. It took me a while to come up with a nice way of solving part 2, but after a few annoying bugs I managed to get it working.
Part 1
Fairly standard, just solve it by looping thru forever until a player has a score >= 1000.
Part 2
The bounds of the 4 important numbers (Player 1 pos, Player 2 pos, Player 1 score & Player 2 score) are all quite limited (1-10 for position, and 0-29 for score), so the possible permutations of the combinations of these values is also fairly bounded (There's not a crazy amount of possibilities), however recursively exploring each of these bounds will lead to a _lot_ of extra work that is mostly pointless as the calculation of wins given an initial p1,p2,s1 & s2 is the same regardless of how we got to that point. So my solution makes heavy use of a 'cache' that keeps track of old situations we've already seen, and returns the pre-calculated values. There are 16,752 actual "calculations" needed, whereas there are then 258,639 cache hits that can return instantly.
1
u/vizyn Dec 21 '21
Groovy
3
u/morgoth1145 Dec 21 '21 edited Dec 21 '21
Python 3 79/29
I've been expecting some sort of iterative game for a few days now, so glad to see that I was right! Part 1 wasn't too bad. I probably didn't need the die generator but it felt right to me.
Part 2 was a twist that I didn't see coming! It took me too long to understand what the quantum die was supposed to do.. I was thinking the problem meant it rolled 1, 2, and 3 in separate universes then continued on but I couldn't find where the rules said that. Once I realized it really meant just those 3 results it made more sense!
Once I realized that, it became a simple recursive memoization problem. I love
functools.cache!Edit: I didn't entirely like the triple nested loop in part2 or the mess of parameters so I refactored it a good deal. It now supports an arbitrary number of players as a result!
3
u/mcpower_ Dec 21 '21
Python, 198/34. Part 1, part 2 is below as it's mostly self-contained.
A nice dynamic programming problem (and therefore use of
functools.lru_cache:P). I suspect my state space can be made smaller, but I'm too tired to think at the moment.edit: okay, after seeing /u/jonathan_paulson's solution here I could've used three for loops instead instead of expanding my state space by a factor of 18...
3
u/hugh_tc Dec 21 '21 edited Dec 21 '21
Python 3, 34/218.
Parts 1 and 2, and (edit) the cleaned-up code.
Is
@functools.cachenot a thing? That tripped me up.3
u/EffectivePriority986 Dec 21 '21
perl5 62/702
My little AoC:
memoizeis magic! Part 2 was lots of fun, except a made a silly mistake of adding together the die rolls because I didn't reset the position when iterating over possible results, hence my 702 position. Took me forever to debug.3
u/rabuf Dec 21 '21 edited Dec 21 '21
Common Lisp
Why optimize when it only takes 3 seconds? Recursive solution for part 2 that almost certainly can be improved with some caching. I did at least cut it down from 27 (3 x 3 x 3) down to 7 rolls multiplied by the number of times they will show up. I wrote two functions and just copy/pasted to handle it rather than passing the current player around in it. Kind of lousy code, but it worked.
player-2is the same. I made the target score configurable just in case this blew up on me so I could use it for testing a faster version (with fewer iterations) but didn't need it.Edit: Rewrote the above so it used memoization. It's now down to ~28ms versus about 2.5 seconds, so around a 100x improvement. I also collapsed the mutually recursive functions into one single recursive function which now looks like:
Where I swap the positions and scores each time to handle changing the turns. In theory, this should also improve the ability of the cache to match prior results.
For part 1 I realized I'd taken too long already so I decided to have some fun. Instead of the modular arithmetic and such (for the dice and the position) I used circular lists:
So determining the next die roll was just summing up the next three elements in the repeating list
1..100and positions were just thenthcdrfrom the current position. I realized I'd have to scrap a lot of logic anyways so I just rewrote it for part 2 with the recursive approach switching fully between each player. I'll probably rewrite to use a turn marker and a pair of arrays like with part 1, but it won't help it run any faster, just cut out half the code.3
u/constbr Dec 21 '21 edited Dec 21 '21
Javascript
Super dumb and straightforward part 1. Recursive computations with cache for part 2 finish in 214ms on my i7-4770.
Github: part 1 part 2
Update: optimised number of recursive calls in part 2, reduced execution time to 131ms.
3
u/michaelgallagher Dec 21 '21
Python
Yay memoization!
I think the hardest part was making the inputs for my recursive function hashable so I could use
lru_cache. Might revist in the morning to see if I can clean up the code a little more.3
u/seligman99 Dec 21 '21
Python, 696 / 311
Spent a long time after getting the answer trying to clean things up. I'm pretty sure my state machine solution is among the worst possible ones, but it does work. Eventually.
github
3
u/DFreiberg Dec 21 '21 edited Dec 21 '21
Mathematica, 116 / 169
So close to the leaderboard, and yet so far. I lost a lot of time on part 2 due to incrementing both players' scores with their current positions every turn; I eventually fixed this and shortened the code a bit by incrementing only the first player's score, and alternating which player is first every iteration, rather than any kind of explicit turn boolean variable. Runtime is 5 seconds.
Part 1:
Part 2:
[POEM]: The Garden of Forking Paths
You saw a flower on the left
Too lovely not to look.
I drifted rightward, from the heat
To find a shady nook.
And from that point our paths diverged
And separately we strolled
Throughout the garden of the worlds
Where trees and dice are gold.
Each garden path, past vine and root,
Continues into three,
But here and there two paths will meet,
Rejoining from the tree.
I wander through the many paths,
And smile at the flowers,
And pretty things that bring to mind
Old memories of ours.
But never do I stop and linger
Longer than a minute;
This garden with its endless green
Has one more flower in it.
I'll wander all the myriad ways
And roll old Dirac's dice,
Until we meet, and hand-in-hand
Can walk through Paradise.
3
u/phord Dec 21 '21
Python
Part1: Played the game straight. This was fairly easy modulo a few typos.
Part2: Count the universes matching each state, where the state consists of pawn positions and scores for both players. Each player takes turns in lockstep in all universes at once, except ones where the game is already won. Then I calculate the new set of universes and discard the old ones that were left behind, but keeping the ones that have finished the game. This continues until there are no unfinished games.
Both parts finish in about 750ms.
GitHub
3
u/fireduck Dec 21 '21
Java 616/189
https://github.com/fireduck64/adventofcode/blob/master/2021/21/src/Prob.java#L73
Pretty standard recursive with memo. It was of course a complete rewrite from part 1, but that couldn't be avoided. No one expects quantum dice.
3
u/Pyrolistical Dec 21 '21
javascript part 2
solution
3
u/VeeArr Dec 21 '21
Java 340/slow
paste
I didn't initially read the updated score limit for part 2, so I was scratching my head and preparing to do something over-engineered. It turned out fine in the end, though I had a silly off-by-one error that took a while to debug in part 2.
3
u/[deleted] Dec 21 '21
Rust paste
First attempt was just memoization with a hashmap, didn't do anything clever. Then I shamelessly stole /u/SuperSmurfen's super nice approach to speed it up by reusing the same code (and thus cache entries) for player 1 and player 2. Finally, swapped out the hashmap cache for a vector-based one. The way I've ordered the dimensions for computing the index probably isn't optimal, but this runs in about 5ms on my laptop so I'm happy.
And yes, I got a measurable performance improvement by listing out all the possible rolls in an array :)
3
u/polettix Dec 21 '21
Just the gist of part2 in Raku.
It's a combinatorial solution that compares the relative merits of playing as 1 or 2 according to the statistic of winning within a certain number of moves, assuming that the other player hasn't won yet.
It's convoluted and there are way cleaner solutions based on recursion and memoization; the only merit is probably that it's a bit more efficient (in Raku, at least, compared to the re-implementation of this Python solution).
3
u/sawyerwelden Dec 21 '21
Julia (3279/511). Made some dumb mistakes on part 1 that cost me a ton of time. Julia proved really nice for part 2 though:
3
u/cetttbycettt Dec 21 '21
R /Rlang
It is always scary when it is past day 18 and part 1 is easy :D.
I was expecting something like AoC 2109 Day 22, but it was easier.
Today was my cheatday as I used the tidyverse library :) github
3
u/hqli Dec 21 '21
Typescript
Hmm... a multiverse branching quantum die that you could remember results from... Why are we still chasing the keys as a single submarine in a single universe again? I vote we roll this dice for a direction to go in until one of our quantum counterparts stumbles on those pesky drifting keys
3
u/WilkoTom Dec 21 '21
Rust
Massively over engineered part 1 as I wrongly guessed that part 2 would either involve more players, and / or involve dice that behaved in a more complex way. I was right, but not in a way that was at all helpful.
Part 2 was a straightforward function:
The trick? Using the
#[cached]attribute macro from the cached crate against means we only ever calculate the number of results for a given pair of player-states once.3
u/relativistic-turtle Dec 21 '21
IntCode
Part 1 was mechanic and not very exciting, but part 2 totally made up for it! I think dynamic programming (mostly implemented using a cache) is a very elegant technique.
Had trouble with my cache though. Hash-values collided because I had assumed (why?!) the score would never exceed 24 for any player at any time. But it can go as high as 30! (Not-winning-score of 20 + stepping on the 10 --> winning at 30). Was hard to debug using smaller examples.
3
u/vegeta897 Dec 21 '21
TypeScript (part 2)
No memoization or caching of game state; I keep track how many times a possibility can occur by recursively multiplying the roll occurrence count for each turn until there is a win, at which point the final occurrence count is added to that player's wins. Runs in about 1.6 seconds on my machine.
3
u/bsterc Dec 21 '21
C++ 5173/3650
I'm failing to grasp this talk of memoization. I'll have to read some solutions. I keep track of the number of universes with each
[p1_score][p1_position][p2_score][p2_position], and play all the turns. It takes about 1.2 ms.3
u/[deleted] Dec 21 '21 edited Dec 21 '21
Pascal 2235/4609 - 203 mSec
After wasting hours because I failed to work out my constants right... I got part 2 figured out correctly, with no recursion, no objects, nothing but a ton of nested loops and global variables.
3
u/DrShts Dec 21 '21 edited Dec 21 '21
Python 3.10 [source]
part 2:
3
u/abeyeler Dec 21 '21
Python
My final code, including some clean-up I initially didn't thing about. Using a frozen
dataclassmade the core function really nice and clean.3
u/Symbroson Dec 21 '21
Haskell without imports
my ram hates me today - Have 8G of Ram and it moved 4 of it to the Swap before being able to give me an answer for the test input. my part 2 didn't need that much memory but still the memory complexity of my code is horrible
saw people using caches here - that might have spared my Ram a little possibly but hey as long as it works its good enough for submission right
3
u/SiloPeon Dec 21 '21
Python solution for part 2. It runs in less than a second but I do have to run it twice because I couldn't figure out how to make sum() work with two values... Oh well, at least it's fairly simple to understand. Though it took me a long time to find out that I was getting incorrect results because I was starting with amountOfRolls at 0 instead of 1, thanks assert.
3
u/[deleted] Dec 21 '21
Java
Basically the idea is to create a map of all possible dice rolls and the number they occur. Then use that to iterate the recursion. Increase the wins by the multiple of the occurrence of the preceding dice rolls. Runs in ~500 ms.
3
u/allergic2Luxembourg Dec 21 '21 edited Dec 21 '21
Python
Runs part 2 in 0.027 seconds. If you put the points to win back up to 1000, it runs in 8 minutes :)
3
u/maneatingape Dec 21 '21 edited Dec 21 '21
Scala 3 Solution
Once I saw the Part 2 sample result knew it had to be a memoization solution.
My favorite bit was the legitimate use of the word
thrice. Especially proud of the variable namediracDiceThriceEDIT: Cleaned up the mess of loops in Part 2 with an approach using
partitionto split the list into winners and undecided at each stage. Feels much more readable.3
u/Dullstar Dec 21 '21
Python
C++
I immediately thought of the lanternfish problem when I saw part 2, but I had to think for a bit to figure out exactly how I was going to apply it.
I use a struct consisting of the score and position of both players, as well as whose turn it is, and then use two dictionaries/unordered_maps (i.e. hashmaps) to check 1) how many of each game state I'm looking at there are on each iteration, and 2) what that state will become on the next turn; since not all combinations of scores are possible (you couldn't, for example, have player 1 at 20 points while player 2 has nothing, as the minimum score per turn is 1 and the maximum is 10), I don't generate these until the first time I need to look it up.
It's really some of these later problems where Python begins to show its major weakness: code that runs perfectly fine when rewritten in C++ can be slow enough for a very noticeable delay in Python. There could very well be a faster way to do it in Python (not counting something like pypy), but there's a lot less wiggle room in Python before the performance gets bad than there is in C++. On my machine, the Python version takes ~1.5 seconds, and the C++ version takes ~100 ms.
The C++ version handles checking wins slightly differently since the Python solution takes advantage of dynamic typing; I thought maybe that could potentially account for some (not much, though) of the slowdown, and tried doing it the same way as the C++ version. It didn't help; it might actually have made it (slightly) worse, which is why I did not commit that change to the Python version.
3
u/jayfoad Dec 21 '21
Dyalog APL
Keeping track of the
+1s and-1s was annoying. Part 2 does dynamic programming, keeping track of how many universes each player wins in, starting from every possible combination of positions and scores.The
0 0 1⍉is only required to do a kind of indexing into z that Dyalog APL doesn't seem to support: I want choose indexing on a pair of axes, but taking all items along a third axis. I suppose you might call this "short choose indexing" by analogy with the "short left arguments" that Squad and Take accept.3
u/Naturage Dec 21 '21
R
Solution here. Another easy one, seems like the worst in in the-
jazz music stops.
Jokes aside, after the initial panic I cobbled together a solution, and then after a bit more - vectorised it enough to run in ~4 seconds. Felt like lanternfish part 3, really.
4 days to go!
Also, huge shoutout to a fellow R AoCer for using unnest() the earlier day - saved me massively here.
3
u/RoughMedicine Dec 21 '21
Python, 0.28ms (PyPy 3.6), 0.42ms (CPython 3.8)
I had a lot of fun today. Realising that you don't need to calculate every single roll, but rather only individual roll outcomes and then multiply the frequencies was the key to me.
3
u/trollerskates1 Dec 21 '21
Scala. Doesn't have the convenience of
functools.cachelike Python, but you can get the same behavior using amutable.Mapand using.getOrElseUpdate!3
u/jmpmpp Dec 21 '21 edited Dec 21 '21
Python 3, using a configuration space to keep track of how many worlds are in each possible configuration of position and score after each move.
3
u/tymscar Dec 21 '21
Probably my favourite day so far. Super geeky, not too easy so I finish it in 5 minutes, not too hard so it takes me the whole day. Love it.
As soon as Ive read part2 I knew I had to memoise the solution, otherwise it would be crazy.
Part1 and part2 in Javascript.
3
u/Bruceab Dec 21 '21 edited Dec 21 '21
Python
https://github.com/Bruception/advent-of-code-2021/blob/main/day21/part2.py
Solved using DFS + Memoization. At each state, try all possible rolls and recursively count the outcomes of the games. There are only ~44,100 possible states. We can memoize the outcome given a state, to avoid exponential time complexity.
The arguments p1, p2, s1, s2 represent:
-The position of the current player
-The position of the next player
-The score of the current player
-The score of the next player
3
u/thulyadalas Dec 21 '21 edited Dec 21 '21
RUST
Memoization is today's word. After an eventful part 1, as soon as I saw part 2, I knew we need to cache seen results.
For a bit, I wasn't sure that each turn will lead to 3 or 33 = 27 subgames/universes. After making sure it's 27 combinations, I initially generated the 27 outcomes and run the game using a HashMap cache and got the part 2 under 8ms.
After examining a bit, we can see that while in the possible outcomes 3 occurs 1, 5 occurs 6 times or 6 occurs 7 times etc. We can reduce the number of calls here if we also just each value once and multiple with its occurrence. Making this improvement in the pre-calculated outcomes, the system runs under 3ms for both parts now.
3
u/No_Plankton3793 Dec 21 '21 edited Dec 21 '21
Rust
Lanternfish again!
The game state (position and score) of both players in part2 can be packed down to fit within 16 bits. So I simulated each possible reality and maintained counts just like with the lanterfish and polymer puzzles.
One small trick I applied to part1 for a small speed boost: The die rolls can be derived from triangle numbers. While the die's state is below 97, I can quickly calculate the roll by taking
triangle(state + 3) - triangle(state)- which simplifies to3 * state + 6.3
u/Sourish17 Dec 21 '21
Python 3
Another nice one today! Solution + mini write ups:
sourishsharma.com
3
u/giftpflanze Dec 21 '21
Factor
I really love my part 2 solution:
3
u/cmukop Dec 21 '21 edited Dec 21 '21
** C++ **
"memory is cheap" option gamestate is encodable in 18 bits so use two buffers to store how many universes in any given state and its really just lanternfish part 2
https://github.com/codemonkey-uk/aoc-2021/blob/main/src/twentyone.cpp
** what went wrong? **
It would've been done much faster if i hadnt forgot to convert the initial state from 1-base to 0-base in the GameState constructor, spent an good hour debugging that.
** thinking face emoji **
it would be a interesting twist to go do this in a compute shader - instead of iterating current states and incrementing the counter for each of their future states, you can predetermine which states any given state derives from, so it becomes n fetch ops from const buffer and one one write per state, then the whole thing is fully parallelisable and could be done as a compute shader on the gpu
3
u/IlliterateJedi Dec 21 '21 edited Dec 21 '21
Python3 Part 2 only - Runs in 800ms or so on my laptop. I completely rebuilt the logic for part 2 so I didn't include part 1. They're both messy (I think the player states could be done more elegantly and then instead of duplicating the p1/p2 code I could just have the player states and which player to play. I don't know how this would work well with the caching, though. Maybe a frozen dataclass or named tuple would have worked. In any event, I am not going to worry myself about it.
I will say that I thought part 2 was the easier of the two parts. For some reason figuring out the 'position > board length' logic tripped me up hard. I set "If position > board length, position %= board length" which is not correct because a position 20 % 10 puts you in position 0. Which then I added 1 to that scenario and that was also not right. I had trouble wrapping my head around setting it to 10. I don't know why. Eventually I got there, but that was harder to me than figuring out the recursive logic of part 2.
3
u/bboiler Dec 21 '21 edited Dec 21 '21
Clojure
3
u/Nanonoob1987 Dec 21 '21
C#
I got the question totally wrong for quite a while. "Find the player that wins in more universes;" more/most, I'll blame my french ! It runs in ~10ms
3
u/zniperr Dec 21 '21
python3:
3
u/karjonas Dec 21 '21
Rust GitHub.
3
u/SomeCynicalBastard Dec 21 '21
Python
source
Brute force for the first part. For the second part I used a defaultdict to keep track of how many games were in each state after each die roll. Given that there could only be 20 points, 10 positions on the board and 2 players, the number of states is limited to around 44000, so this is doable.
Runs in 0.4s for both parts.
3
u/RewrittenCodeA Dec 21 '21
Elixir
40 LOC, ~1 second when run as stand-alone
exsscripthttps://github.com/brainch-dev/aoc.ex/blob/main/2021/21.exs
3
u/mine49er Dec 21 '21
PHP
0.1 seconds for part 2 on an 8-year old MacBook Pro (2.6 GHz Core i7).
Around 13 seconds without memoization.
paste
3
u/kuqumi Dec 21 '21
Javascript
In part two I calculated how many ways each three-dice sum could happen and then in my recursive function I multiplied the win counts by that factor. I don't know how much time that saved but I saw the huge number in the sample answer and assumed that kind of thing would be necessary.
3
u/drbolle Dec 21 '21
Yet another Kotlin solution. Not the most elegant.
https://github.com/ThomasBollmeier/advent-of-code-kotlin-2021/blob/main/src/de/tbollmeier/aoc2021/day21/Day21.kt
3
u/shouchen Dec 21 '21
Easy-to-understand C++ solution
https://github.com/shouchen/AdventOfCode/blob/master/aoc2021/Day21/Day21.cpp
3
u/veydar_ Dec 21 '21 edited Dec 21 '21
Lua
Misunderstood part 2 at first but I knew it would be a dynamic programming thing simply based on the task itself. This let me eventually clear up my misunderstanding. Had an ugly solution where I always switch between player 1 and 2 based on a toggle, and then saw this beauty so I stole that clever switching.
Repository
3
u/aardvark1231 Dec 21 '21
My C# Solution
Had the logic correct right up until I was calculating victories. I didn't notice that I was returning too early and cutting out a bunch of rolls. Moved the returning statement of my recursive function and got the right answer. Took all day to spot that error... ooof.
3
u/RubenSmits Dec 21 '21 edited Dec 21 '21
Most of you have way better solutions than me so don't look to long :)
Only thing I want to add is that from my start positions 1 and 10 it was clear player 1 was going to win. On average you throw 6 so on average after both roll, player 1 has 7 points and player 2 has 6 points. So I only took track of player 1 wins which made it a bit easier.
My solution: Python3
3
u/dizzyhobbes Dec 21 '21
Go/Golang
All caught up for all 7 years! Such a simple problem statement and input but such a great prompt today.
https://github.com/alexchao26/advent-of-code-go/blob/main/2021/day21/main.go
3
u/Imaginary_Age_4072 Dec 21 '21
Common Lisp
I'm really impressed at people who manage to solve these really late at night. I did part 1 last night and spent ages struggling with part 2 so went to bed, and then it only took 20 mins once I came back to it today fresh.
My first solution for part 1 was about 40 lines long + some helper functions, but I managed to strip nearly all of it out using recursion:
And for part 2, I originally was working backwards - I wrote a recursive function that you gave the two player's positions, scores, start positions, and which player's turn is was and the function would say how many universes that state happened in. Then I ran that function for every square that either player could finish on and for every score that each player could have, and summed up the wins. It got the right answer and it in the github history if anyone's interested, but I managed to simplify it to the one below which tracks both players wins forward.
This already has a fairly acceptable runtime without any optimization for the numbers given (about 7 seconds), but memoizing it brings the runtime down to about 0.2 secs. There are already libraries for this but I decided to write my own.
3
u/RookBe Dec 22 '21
rust
3
u/cloud08540 Dec 22 '21
Python
Part 1 was a ruse to keep us off balance for part 2 ;) Took a little while to realize why my code wasn't capturing every timeline, but it was just a problem with how I was keeping track of wins...
https://github.com/danielgaylord/advent-of-code/tree/main/2021/Day%2021%20-%20Dirac%20Dice
3
u/sortaquasipseudo Dec 22 '21
Rust
This problem was time-consuming, but ended up being much less scary than I originally thought. Part 1 is fiddly but straightforward to implement, but I found Part 2 much more challenging. I had the intuition that it was a recursion problem, but I had to get up and do something else before the exact solution came to me. One thing that helps simplify the recursion code is enumerating the 27 die-roll outcomes for a single player's turn, and reducing that to a map between totals and frequencies.
I'm live-streaming my solutions via Twitch. Please stop by and help me out in the chat! Video archive is here.
3
u/SplineGopher Dec 22 '21
GOLANG
Kinda funny ! I Use struct to represent board and player
for PART 2, I use a cache + calculate how many universes can be created when lauching three time the dirac dice (If we get 9 then only one, 7 universes were we get 6, ....)
https://github.com/Torakushi/adventofcode/blob/master/day21/day21.go
Have fun !
3
u/RiemannIntegirl Dec 22 '21
Python 3.9
In Part 2, the key idea I used was to store a dictionary of states:count of games in that state, where state was a tuple of: (p1 position, p2 position, p1 score, p2 score) - there were 44,100 such states.
Part 1
Part 2
3
u/1e9y Dec 23 '21
my awkward golang solution with recursion:
https://github.com/1e9y/adventofcode/blob/main/2021/day21/day21.go
part 1 computed in ~5ms
part 2 computed in ~120ms
somehow it still feels that second part must have nice analytic solution...
3
u/bozdoz Dec 23 '21
Go! Golang! https://github.com/bozdoz/advent-of-code-2021/blob/main/21/dice-game.go
read and used u/SplineGopher's solution
1
u/levital Dec 21 '21 edited Dec 21 '21
Haskell
(Part 1 only, sort of. Need to manually search for the winning turn.)I hate these modulo puzzles. This is way worse than day 19, and I just wasted an entire workday on part 2 without getting anywhere. Screw this. Another year of failing to get all the stars I guess.More than 10 hours later, I finally figured it out. Part 1 unfortunately made me think in the completely wrong direction. Code is awful and I don't really understand it anymore, but very much to my surprise it finishes in 0.02 seconds. I can only guess that GHC adds some automated caching when compiling with -O2, otherwise this performance makes no sense.
2
u/MichaelRosen9 Dec 21 '21
Julia 1838/691
I feel like this was the biggest change between part 1 and part 2 problems this year - I was more expecting something along the lines of "run for an insane number of iterations". Solved with dynamic programming - the recursive function will be called at most 24 * 24 * 10 * 10 * 6 = 317400 times, as this is approximately the number of accessible unique game states (the real number is a bit less than this because there is no game state where both players have a score >= 21). It is also possible to speed up the dynamic programming approach by exploiting the symmetry between player 1 and player 2's scores and positions and the "roll/turn" indicator - this will reduce the number of function evaluations by a factor of two.
2
u/uncountablyInfinit Dec 21 '21
Python, 1902/554
Lost like 5 minutes on part 1 because I was overconfident and manually (incorrectly) copied the answer into the box instead of copy/pasting, fml
2
u/mental-chaos Dec 21 '21
Python 3 716/289
My part 2 reduced the number of universes needed by precomputing what 3 rolls of a 1-3 die can produce.
2
u/surplus-of-diggity Dec 21 '21
Python 1182/757
I had a lot of typos what slowed me in part 1, and part 2 I thought this wouldn't work at first.
paste
2
u/Imnimo Dec 21 '21
Python (341/96)
https://pastebin.com/E4sY874f
I was expecting part 1 to be what part 2 ended up being, so I was ready to go on that part. Spent a little too long hammering out part 1 (always be careful not to name your variable and your function the same thing...), but made up time on the second half.
2
u/DARNOC_tag Dec 21 '21 edited Dec 21 '21
Rust 530/535
Part 1 was fairly nice in Rust.
For part 2, I used a pretty naive game-tree search rather than the DP / memoization some others used. It runs in 2.5 seconds; good enough. I lost some time by accidentally starting the game with players in position 0, instead of the puzzle input (only in part 2).
2
u/TheZigerionScammer Dec 21 '21
Python 1545/916
Part 1 was fairly starighforward, I lost a couple minutes because of some stupid typo mistakes that game me the wrong answer but I think a programming student of two weeks could solve part one so I won't dwell on it, my Part 1 code is on the bottom commented out. For part 2, boy, I knew I wouldn't be able to simulate that many universes, but after thinking about it I didn't have to. I didn't need to separate each universe after every die roll, just after every turn. So I quickly calculated the likelihood of each outcome of 3 through 9 to occur and kept track of the "weight" of each event. After that breakthrough it's just a simple recursion, do Player 1's turn, then do player 2's turn with every possible movement, etc. I believe this technically makes it a DFS approach but it worked the first time I tried it so I coded it all right. There's a lot of copy pasting in there, especially when it came to splitting the timelines, it was easier for me to type it all out in the code than make a for loop with a list. I might clean it up later. The run time is 16 seconds or so, which I'm fine with.
Paste
2
u/Ph0X Dec 21 '21
Python 547/1033
part1
part 2
2
u/LtHummus Dec 21 '21
Scala
Good to finally be back on track...I was traveling a bit so I have slowly been catching up (and now I'm finally caught up!). Part 1 was pretty straightforward. Part 2 I had a working algorithm, but lost time due to stupid bugs (making the quantum die 0, 1, 2 instead of 1, 2, 3).
Ugly code tonight with copy and pasting, but whatever...it works. That said, I did use the (horror of horrors!)
mutable.HashMapto keep a cache of the quantum game states...I think I'll add some sort of genericmemoizeutility to the toolbox for next yearCode is right here!
2
u/francescored94 Dec 21 '21 edited Dec 21 '21
Nim solution both parts in 0.2ms (200μs for running binary+loading file+solving both parts on m1 air) today was a classical exercise in DP, very enjoyable since state does not propagate unconditionally
code original + code fast part2
2
u/DrunkHacker Dec 21 '21 edited Dec 21 '21
Javascript part 2
Pretty straightforward implementation. Code ended up mostly readable aside from stuffing the state of the universe into an array. Runs in ~300ms.
2
u/C2thehris Dec 21 '21
Javascript
First sub-1000 finish for me with part 1! Finished 829th. Made a very silly mistake for part 2 at first, where I forgot that the game was only scored every third roll, and then had a small bug where I forgot to change a loop index from a copy and paste which took me 10-15 minutes to figure out. Overall I am happy, just gotta read more carefully!
2
u/lacuno123 Dec 21 '21 edited Dec 21 '21
Javascript with a non-dp approach and no memoization.Recursions go brr!
Still runs in 1323ms on my machine.
2
u/Cpt__Cookie Dec 21 '21
Python
git
2
u/schovanec Dec 21 '21
My solution in C#: GitHub
2
u/Gurrewe Dec 21 '21
Go (golang) (1123/2210)
Recursive with memoization. I've seen a few smart tricks in the thread of others that are flipping scores and positions each turn - that's cool! I instead tracked another variable for who's turn it is.
Code
2
u/DrSkookumChoocher Dec 21 '21 edited Dec 21 '21
Deno TypeScript
979/477. One day I'll make it on the leaderboard... maybe.
Here's my part 1 and 2 after a lot of optimization. Originally they both used Arrays to store positions and scores. That turned into a little bit of a hassle for part 2 though because of their mutability. Originally part 2 used string based keys. Now it uses keys based on the state turned into a number. It may even be able to be optimized further (search space cut in 2) if you could remove the 'is player 1's turn' part of the key, but I think it's fast enough at ~25ms.
https://github.com/N8Brooks/deno_aoc/blob/main/year_2021/day_21.ts
Updated by making the states player 1/2 agnostic as mentioned previously. The trick is to not pass player 1/2. Just swap scores and positions! Now the runtime is ~15ms.
2
u/Mintopia_ Dec 21 '21
PHP
GitHub
Part 1 was straight forward enough. Used some helper classes for tracking everything.
With part 2 I attempted to re-use things, but couldn't really. Recursive function for calculating based on state of the game. Used memoization (TIL that the technique I've been using for years has an actual name.) to reduce it to only 16,497 calls.
2
u/PendragonDaGreat Dec 21 '21
C# 3823/2712
Code On Github
Abusing Tuples and Deconstructors for fun and
profitstars.Simple iteration for part one, memoization for part 2. ~200ms total run time.
2
u/chthonicdaemon Dec 21 '21
Python
Straightforward recursion with memoisation for Part 2, total solve time 200ms. I think I saved some lines by just encoding the scores/positions in a list rather than handling player 1 and 2 separately.
2
u/oddrationale Dec 21 '21
F# solution in Jupyter Notebook. Got some help from this thread.
2
u/fiavolo Dec 21 '21
Python
It was pretty clear from the big numbers in Part 2's example that brute force wasn't going to cut it this time xD.
I used memoization to store the number of ways that a player can earn X points by turn Y, while ending on board position Z. With this, I could calculate the number of winning scenarios for a player as (The number of universes where he earns enough points to win on the nth turn) * (The number of universes where the other player hasn't earned enough points to win by then), summed over a set of values for the number of turns.
2
u/gralamin Dec 21 '21
Rust
I wasted a lot of time on the quantum game not properly including the turn order in my cache, which caused me to lose ~400 trillion universes. I prefer to treat my rust more object oriented then is strictly necessary.
In brief:
2
u/gyorokpeter Dec 21 '21
Q: paste
2
u/Perska_ Dec 21 '21 edited Dec 21 '21
C# https://github.com/Perska/AoC2021/blob/master/AoC2021/Days/Day21.cs
Spent way too long trying to figure out why the program was going so fast and returning small values for part 2. Turns out I forgot that you still had to throw three die, not just one.
I then experimented with cache, but forgot to actually return early if there was data in the cache, which caused the program essentially ignore it.
One return statement later, the program completed in mere milliseconds?! I knew that caching is powerful, but still, I had an IRL "what the heck" moment.
2
u/Spex_guy Dec 21 '21
Zig: 800 trillion universes in under 200 microseconds
https://github.com/SpexGuy/Advent2021/blob/main/src/day21.zig
Found a nice trick where the two players can be simulated separately in isolation, and then that info can be combined to figure out the results when they play against each other.
2
u/phaiax Dec 21 '21
Python
Part 2 runs a lot faster than part 1 :D
2
u/xelf Dec 21 '21 edited Dec 21 '21
Python, abandon all hope style guides...
part1:
part2:
2
u/JaegerMa Dec 21 '21
ABAP
Github
2
u/KingFlerp Dec 21 '21 edited Dec 21 '21
Verbose C++20 Part 2 - lots of optimisations left on the table, as I prefer things to be a bit more straightforward :)
https://pastebin.com/H0sBsmVq
Edit:
Figured out what I was doing wrong when trying to use the spaceship operator XD
https://pastebin.com/x1NsHLDN
2
u/mapleoctopus621 Dec 21 '21 edited Dec 21 '21
Python
Fun problem! I use the counts of possible outcomes for each round of 3 dice rolls and calculate the counts of all possible (score, position) pairs. For each winning score, the number of winning universes is (count of that score) * (number of non-winning games of opponent).
I wasn't getting the right answer at first because apparently I modified the
positionslist when doing part 1, so part 2 was calculated for a different starting position. A good way to debug today is to work it out by hand for some small winning score like 5.This executes in a few seconds even if the winning score is 500.
2
u/Diderikdm Dec 21 '21 edited Dec 21 '21
Python:
2
u/axr123 Dec 21 '21 edited Dec 21 '21
Python
I explicitely branch on each die roll, not only when players are taking turns. Makes it less efficient, but I found it clearer that way. Part 2:
2
u/ICantBeSirius Dec 21 '21 edited Dec 21 '21
Swift
Runs part 1 and part 2 in about 230ms on my computer. Got my best rank yet for part 1: 2024.
Gonna go look and hopefully see some visualizations of 100 sided and 3 sided dice.
2
u/wasi0013 Dec 21 '21
Elixir
Enjoyed this one!
y2021/day_21.ex
2
u/MarcoDelmastro Dec 21 '21
Python
https://github.com/marcodelmastro/AdventOfCode2021/blob/main/Day21.ipynb
(simple naive recursive solution for Part 2, then realised I could reduce the recursion space since the 3-dice trowing sequences don't all yield different counts - i.e. it's like trowing 3 dice at once and sum the outcomes)
2
u/vss2sn Dec 21 '21
Solutions in C++:
Part 1
Part 2
(As always, each file is a self-contained solution)
2
u/kupuguy Dec 21 '21
Python solution. https://github.com/kupuguy/aoc2021/blob/main/src/day21.py
I worked out the answer as the number of ways for the player to win in a set number of turns multiplied by the number of ways that the other player lost in either the same number of turns (for p2 winning) or one fewer (p1 winning) summed over all reasonable numbers of turns.
Then the ways to lose in a set number of turns is the sum of all the ways to reach a score under 21 in that many turns.
The way to win in a set number of turns is more complicated as the previous move has to be to a non-winning score. That tied me up for a while until I found I had a `max` where I should have had `min`. Tricky one to debug when the answer is either right or not, and there are no simple cases to verify against.
Takes about 0.25s
2
u/cascer1 Dec 21 '21
Kotlin 7329 / 4131
source
Part 1: 2 ms
part 2: 143 ms
A classic case of keeping states and then it was relatively simple. Didn't end up having to recurse which is always nice.
2
u/freezombie Dec 21 '21 edited Dec 21 '21
Rust
Part 1: https://github.com/tjol/advent-of-code-2021/blob/main/21/src/puzzle1.rs
Part 2: https://github.com/tjol/advent-of-code-2021/blob/main/21/src/puzzle2.rs
Spent some time banging my head against the wall because I was getting results orders of magnitude lower. Turns out I hadn't understood that the bit about throwing three dice per turn applied to part 2 as well.
In part 2, I'm keeping track of how many universes each possible game state shows up in after n turns in a state -> frequency map (
HashMap<GameState, usize>)2
u/CounterDesk Dec 21 '21 edited Dec 21 '21
Python
I kept track of how many times each universe occurs and then then just played the game with pre-calculated (and counted) outcomes of the special die
2
u/semicolonator Dec 21 '21
Python, 39 lines
Using a recursive solution for part 2. For all dice sums check, does player one win? If yes, go to the next dice sum. If not, swap players and recurse.
2
u/aurele Dec 21 '21
I am quite happy with my second iteration of today's solution in Rust using memoization: https://gist.github.com/samueltardieu/ec5ca99195028345c9b9a1035211552f
The first version I wrote used a handmade states cache with a count of the number of paths bringing to a similar situation and took ~400ms, while this one takes around 6ms.
2
u/sseldi Dec 21 '21
Elixir
Bruteforce for part 2. Reduces the number of universes explored, by keeping a count of universes with the same dice sum for a player's turn.
2
u/pavel1269 Dec 21 '21
Rust
https://github.com/pavel1269/advent-of-code-2021/blob/main/src/day21/mod.rs
2
u/seba_dos1 Dec 21 '21 edited Dec 21 '21
Python 3 (no imports, no cache, 24 lines, 50ms)
I think this was the hardest day so far for me - however, had some fun afterwards trying to generalize the solution. In the end I managed to have a single code path that works with both types of games and should be able to handle arbitrary number of players - and all that in just 24 somewhat reasonably sized lines :)
https://gitlab.com/dos1/aoc21/-/blob/main/day21.py
2
u/bZea Dec 21 '21 edited Dec 21 '21
Elixir
For p1 used streams to imitate infinite dice rolls. For p2 had to refactor to be able to cache effectively using Memoize. Finishes in ~500ms.
2
u/mzeo77 Dec 21 '21
Python part2, tweet sized @ 266 chars
2
u/UnicycleBloke Dec 21 '21
C++: https://github.com/UnicycleBloke/aoc2021/blob/master/day21/day21.cpp
I foolishly spent over an hour farting about with matrices thinking I could calculate the wins that way. Then when I settled on a recursive approach for turn taking - with a cache for counts - I struggled for an age to find a key (a hash of the state) that actually worked. Everything I tried gave numbers for the example in the right ballpark (only off by 10 trillion), and I kept getting different numbers for very subtle changes in the code. The final key is the stupidest thing - just concatenate the values from the state vector. So much time wasted! Bah! Humbug!
2
u/mrjnl3 Dec 21 '21
Java part 2
2
u/Ill_Swimming4942 Dec 21 '21
https://github.com/davearussell/advent2021/blob/master/day21/solve.py
Python. Strategy in part 2 is to track the number of worlds in each possible state after each turn. While there are trillions of worlds there are only about 100k possible states so storing them all in a dict is no problem. Runtime is about 0.16s.
2
u/Brytnibee Dec 21 '21
Day 21 Solution in Python
Part two runs in about two minutes for me, which isn't too bad I think. Grouping the "universes" turned out to be easier than expected
2
u/p88h Dec 21 '21 edited Dec 21 '21
Elixir,
167 ms on Part 21.4ms on Part 2Python,
~90ms on Part 2 w/Python or ~60 ms w/PyPy1 ms on Part 2 (w/Python)Same basic algorithm, state-count map replication.
Update: But now dimension independent and 100 times faster.
2
u/ethsgo Dec 21 '21
Solidity (and Javascript) - https://github.com/ethsgo/aoc
P1 is straightforward
The code for P2 is also straightforward
While the algorithm is correct (we know that because it outputs the same values as the Javascript solution when we run it on smaller depths), it doesn't (yet) run for the full depth of 21.