r/adventofcode • u/daggerdragon • Dec 08 '23
SOLUTION MEGATHREAD -❄️- 2023 Day 8 Solutions -❄️-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
Outstanding moderator challenges:
Community fun event 2023: ALLEZ CUISINE!
- Submissions megathread is now unlocked!
- 14 DAYS remaining until the submissions deadline on December 22 at 23:59 EST!
AoC Community Fun 2023: ALLEZ CUISINE!
Today's theme ingredient is… *whips off cloth covering and gestures grandly*
International Ingredients
A little je ne sais quoi keeps the mystery alive. Try something new and delight us with it!
Code in a foreign language
- Written or programming, up to you!
- If you don’t know any, Swedish Chef or even pig latin will do
- Test your language’s support for Unicode and/or emojis
Visualizationsusing Unicode and/or emojis are always lovely to see
ALLEZ CUISINE!
Request from the mods: When you include a dish entry alongside your solution, please label it with [Allez Cuisine!] so we can find it easily!
--- Day 8: Haunted Wasteland ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks
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:10:16, megathread unlocked!
52
Upvotes
13
u/stevie-o-read-it Dec 08 '23
[LANGUAGE: Perl] [LANGUAGE: Latin] [LANGUAGE: Lingua::Romana::Perligata] [Allez Cuisine!]
The suggestion of code in a foreign language brought to mind an old gem. Perl version 5.8 made it possible for scripts to import a module that controls the parsing of the rest of the file.
Just Because He Could, Damian Conway celebrated the new millennium by creating Lingua::Romana::Perligata, a Latin-inspired language that internally translates to Perl code.
I spent way too long trying to learn this horrible language and dealing with a severe number of parsing bugs (I ran up against a number of parsing bugs. Also, left turns were tricky, because it steadfastly insists on interpreting "L" as the integer 50, even when told that it's a quote. Several examples given in the documentation do not work as-is.)
Just install Lingua::Romana::Perligata and run
perl day08.pl day08.txt.It only does part 1. Part 2 would be a nightmare due to severe parsing bugs in the expression evaluator (the keywordsto explicitly specify parentheses do not appear to work).
https://raw.githubusercontent.com/Stevie-O/aoc-public/master/2023/day08/day08.pl
(Chrome recognizes it as Latin and offers to translate. It does a passable job, given that it's not really Latin. I especially like how it translated the conditional expression of the final
whileloop.)4
u/JustinHuPrime Dec 08 '23
[LANGUAGE: x86_64 assembly with Linux syscalls][Allez Cuisine!]
Part 1 was implemented pretty much following the problem statement - I chose to represent the map using a dense data structure (since, after all, RAM is cheap enough that I can ask for 26^3 * 4 bytes (~70kib) just because). I parsed the instructions and the map, but I found I couldn't zero-terminate my instructions, since I was representing left as zero and right as two (since these were actually memory offsets). I thus used
0xff- something thefullptrfolks might appreciate. The map was parsed as follows - I treated each node as a base26 integer, where the first is an index into an array of pairs of words, and each word is the index that the left and right nodes lead to.Part 2 wasn't too much of a change. I had to remember, while parsing the map, which nodes were starting nodes (i.e. last digit of the base26 number was zero), and stored that in an array. Alas, the trick to take the LCM of each individual starting point's steps to the end was spoiled - I'm not sure how I would have figured that one out without spoilers, since it's not explicitly stated that there are cycles. In any case, I took the LCM of the number of steps from each starting node to each ending node. I'm glad I chose to use the spoiler, though - doing a direct search would have taken forever, given that the answer turned out to be around 13 trillion! I did have to write an LCM function in assembly, which is actually really elegant - you'd multiply the two numbers together, then divide by the GCD. With the way
mulanddivwork, the result from multiplying is in the same place as the input to a division. I also didn't have to worry about overflow at any point, since I was using unsigned operations, and those use 128 bit integers when relevant - thecqoinstruction is your friend here (although, upon second thought, it isn't - I should have just donemov rdx, 0, since I don't want to sign extend, andcqosign-extends).I'm also going to argue that assembly counts as a foreign (programming) language for me - or, if that doesn't count, it's almost certainly a foreign language for you. Thus, allez cuisine!
Part 1 runs in 1 millisecond, part 2 runs in 2 milliseconds; part 1 is 8200 bytes long, part 2 is 8688 bytes long.
4
u/Small_Possibility173 Dec 08 '23
[Language: RUST]
https://gist.github.com/PrakharSrivastav/b156e07452a79314b12052ac4594f4c2
Pardon my math but could someone please explain to me why this is an LCM problem? I tried brute forcing part 2 that did not work. At this point I looked into this mega thread that indicated on LCM of step counts of individual nodes .
4
u/ExtremeAdventurous63 Dec 11 '23
[Language: Python]
solution
## Part 1
Just build an adjacency matric from the input map and navigate through the nodes until you get to the node 'ZZZ'
- parse_network runs in O(n) time.
- The while loop in *solve* keeps running until current_position becomes "ZZZ". The number of iterations depends on the structure of the network and the given route. Let's denote the number of iterations in the while loop as p.
- Inside the loop, navigate is called, which has a time complexity of O(m), where m is the length of the instructions, i.e. the route to follow
- Considering that the length of the route is constant (it's fetched from problem_input[0]), the overall time complexity of solve can be approximated as O(n + p * m).
## Part 2
Considering that:
- the problem tells us that the number of steps to get to the arrival point is somehow constant with respect to the length of the route (it must be at least a multiple of the length of the route, otherwise the map would make no sense),
- There must be cycles going from any starting point to each respective arrival point to make the problem solvable, given the previous point
Our goal can be split into three pieces:
Let's consider the example:
We have two starting points: `11A, 22A`
We reach a final point from `11A` iterating only one time over the given route, which is in 2 steps
We reach a final point from `22A` iterating 3 times over the given route, which is in 6 steps
The least common multiple between these two numbers is 6, which is our solution
2
u/Hungry_Mix_4263 Dec 08 '23
[LANGUAGE: Haskell]
https://github.com/alexjercan/aoc-2023/blob/master/src/Day08.hs
At first I thought it was gonna be a graph problem, that was close. Somehow managed to figure right away that part 2 was a lcm problem.
2
u/[deleted] Dec 08 '23 edited Jul 22 '24
crush amusing oatmeal squeamish impossible spectacular crown advise weary boast
This post was mass deleted and anonymized with Redact
2
u/WhiteSparrow Dec 08 '23 edited Dec 08 '23
[LANGUAGE: UIUA]
Uiua is fun! Single caveat - I calculated the LCM of the solutions in Excel...
2
u/Professional-Top8329 Dec 08 '23 edited Dec 08 '23
Both parts golfed in Python (180 bytes). Any improvements are welcome.
2
u/philippe_cholet Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Rust]
My rusty-aoc repo & today' solution here.
Slowest solver so far ^^: 3ms+ to solve both parts. 9-10ms to solve days 1-8.
I thought I would need more than a LCM for part 2. If Z positions were only periodic after some steps... but no. When I saw this, I first computed the LCM outside my code as it was faster. Apart from that, it was easy enough. I even solved this faster (part 1: 26mn24s, part 2: 18mn24s, polish code: untimed) than yesterday.
2
u/efvincent Dec 08 '23
[LANGUAGE: Haskell]
Github
This one was familiar - right away recognized the lcm problem type from past years. Brute force not an option. Was able to skip the hours of hair pulling - starting to feel like a real AoC veteran now :D
2
u/Apprehensive_Pop_43 Dec 08 '23
[LANGUAGE: Haskell]
Part one went really fast. Part two, first attempt with brute force was too slow. Second attempt I tried to compute the cost to go from '..Z' to '..Z' from a given instruction and realize that lcm was sufficient. Did I get lucky with my input data or was there something I missed in the problem that guaranteed that lcm would be sufficient?
Github link
2
u/RaveBomb Dec 08 '23 edited Dec 08 '23
[LANGUAGE: C#]
Based on experience with previous years puzzles, I knew it relied on factorization, but it took me poking at the factors for a while before I recalled the term "Least Common Multiple". Once I had that, everything fell into place.
This is the LINQ-ed calculation for part two. GetSteps() is a simple function to calculate the steps from any starting point in the map. The magic 'true' is to change the break condition for part two, which is basically the only line of code in it that changed between the parts.
Full code at my Github Repo
2
u/e_blake Dec 09 '23 edited Dec 11 '23
[LANGUAGE: m4, Pig latin] [Allez Cuisine!]
m4 -Derbosevay=1 -Dilefay=input ayday08yay.em4yay
Computes the answer in about 1 second, using only Pig Latin, AND with a Unicode progress indicator! (Okay, a Unicode ellipsis is not that impressive, but m4 is strictly byte-oriented and doesn't understand Unicode, so merely passing through raw bytes and letting the terminal do the real work is the best I can do):
I had WAY too much fun translating (and debugging) my original English solution day08.m4 into this one. It's also nice that m4 lets you redefine EVERY builtin macro to a more convenient name. So, for example, my parser looks like this:
And I'm pleased that I coded my original without reading any of the megathread or main thread, so that I didn't get any spoilers. Depends on my common.m4 and math64.m4 helper code from prior years, but at least the solution doesn't require any 64-bit division (at least, not if my assumptions hold that each input reaches a cycle at exactly the point where the direction string has been consumed a prime number of times. If the direction string length were non-prime, or one of the paths has a prefix that results in the cycle occurring at some offset into the direction string, or if the cycle length is a composite number, I've got problems, where I'd have to write a full-blown GCD/LCM computation).
2
u/nalta Dec 19 '23 edited Dec 20 '23
[Language: Gephi]
Part 2 Solved with no code:
Import the graph into Gephi, coloring the source and target nodes, as well as the left and right transitions. Position the nodes using the Yifan Hu Proportional Layout. Identify 6 cycles, each containing one source and one target.
https://imgur.com/PxzItla
Identify that the cycles contain pairs of nodes with complimentary left and right transitions, EXCEPT for a pattern towards the end of each cycle, which would require four right transitions in a row to reach the target.
https://imgur.com/s9DQOEF
Identify that the traversal sequence only contains one substring of four consecutive right transitions, which happen right at the end.
Count the length of all six cycles, and count the number of steps in the transition sequence. Stick those numbers in a least-common-multiple calculator.
https://imgur.com/FJdcq7L
34
u/Smylers Dec 08 '23
[LANGUAGE: Vim keystrokes]
Load your input, type in the following, and — after a brief pause — the cursor will end up on your part 1 answer. Go on, give it a go — it's reasonably short and easy to type today (it's a bit nicer to watch if you first do
:se shm+=s, though that doesn't change the result):To follow the steps, it physically bounces around the input using
/^ABCto jump to theABCnode. At any node it needs to pick the appropriate label on that line to jump to, based on the next direction. Handily (thank you, u/Topaz2078!) they each follow different punctuation symbols, so forLwe can typef((to move to the opening paren just before the left node) and forR,f,(because there's a comma before the right node).Vim keystrokes doesn't really do if conditions, though. Avoid the need for this by turning the directions into equivalent Vim keystrokes. That's what the first line does: replace each
Lin the directions byf(and eachRbyf,— each direction is now a pair of Vim keystrokes that will take us to the next node to use.Which means that the main loop has these steps:
⟨Ctrl+A⟩to increase the number there by 1. This is our step counter.⟨Ctrl+O⟩to jump back to where we were — the node we're currently processing.@-to run a keyboard macro of the keystrokes stored in the"-register. That's the small-delete register, where the keystrokes deleted with2xwere stored. So this is the bit that performs eitherf(orf,depending on the current direction.wto move off the punctuation symbol on to the next node label itself, thenyiwto yank it into register"0./search, using⟨Ctrl+R⟩0to insert the contents of"0into the search string, so we jump to the line for the next node.The step counter is initialized with
o0at the beginning, which isn't an early appearance of one of the ghosts from part 2, but inserts line 2 containing a zero.To make the main loop end when it reaches
ZZZ, we need a command which will fail when it gets there. (I told you Vim doesn't do ‘normal’ if conditions.) So before the loop starts, go toZZZ(which would be cheating if you're actually on a camel) and delete the decoy next nodes that are listed there. This means that when the loop eventually reachesZZZand tries to follow the next direction, thef(orf,will fail, because there isn't a(or,on that line.At which point we've just overcounted by 1, because that last step didn't actually happen. So
⟨Ctrl+I⟩to return to where we were when we last did⟨Ctrl+O⟩(that is, the step counter) and⟨Ctrl+X⟩to reduce it by 1.I hope that makes sense, and do try it out. The loop takes about 15 seconds on my laptop. (I'm not doing part 2, though; multiple parallel locations isn't really Vim's strength!)
22
u/rogual Dec 08 '23
[LANGUAGE: Python] 388 / 4251
paste
I still don't really understand this one, to be honest.
I figured the path each ghost takes from
**Ato**Zwould have to have a loop in it, so I wrotedescribe_pathto describe, for a given starting point,(node, position_in_instructions))**Znodes found along the wayI spent almost an hour trying to figure out how to compute the solution with this information, until I visually inspected it, had a hunch, and did some calculations...
...and it turns out that for each path, there's only one
**Znode before it loops, and the loop destination is always N steps from the start, while the point it loops from is always N steps after the**Znode.So, neatly, each path behaves as a simple oscillator and they're all synchronized.
So the solution just becomes
lcm(steps_to_first_z for each path).Easy, but how were you supposed to know you could assume all that? Perhaps there's some maths I'm missing where you can prove it has to be the case.
17
u/leijurv Dec 08 '23
[LANGUAGE: Python3]
5th place on part 2! 🎉🎉🥳🥳
88th place on part 1
I got so excited that it was a LCM problem that I forgot that python has math.lcm and I instead opened Mathematica as you can see in the screen recording hahaha, I put in the proper math.lcm solution into the paste:
paste
Screen recording: https://youtu.be/APuwchA16B0
15
u/jonathan_paulson Dec 08 '23
[LANGUAGE: Python 3] 64/220. Solution. Video.
The input for part 2 was constructed very nicely so that each cycle hits 'Z' at every multiple of the cycle length, so the answer is just the lcm of the cycle lengths. In fully generic input, they could have some offset (e.g. cycle 0 hits 'Z' at times a+b*k for all integers k), in which case you could solve the problem with the Chinese remainder theorem.
14
u/adamsilkey Dec 08 '23 edited Dec 08 '23
[Language: Python]
Code
LCM, as everyone else has done. I don't think there's any reasonable way of doing it brute force.
If I could do 1 million steps per second, with my puzzle input, it would still take 182 Days to solve via brute force for part 2.
13
u/timvisee Dec 08 '23
[Language: Rust]
Using binary encoding and a lookup table on the stack for extra speed. Day 1 to 8 still under 1 millisecond in total! 🚀
12
u/Synedh Dec 08 '23 edited Dec 08 '23
[Language: Python]
Short parsing thanks to unpack and slicing.
I used the int boolean value for left and rightDon't even need that, dict works faster. LCM is the way, but that seems too convenient, I'm definitvely frustrated.10
u/4HbQ Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python] Code (9 lines)
Nothing fancy today. I was expecting to need to find a shortest path in part 2.
Today's Python trick: 2-element list indexing using a boolean (which is just 0 or 1):
I've used it to update the position based on the L/R instruction:
10
u/odnoletkov Dec 08 '23 edited Dec 08 '23
[LANGUAGE: jq] github
10
u/sedm0784 Dec 14 '23
[LANGUAGE: Vim keystrokes]
Part 1
how it works
8
u/Cross_Product Dec 08 '23
[LANGUAGE: Swift]
Previous years prepared me for this one 😅
Day 8 in Swift
6
u/thepolm3 Dec 08 '23
[LANGUAGE: Rust]
A fully correct solution for generalised input, making use of the made after finding the answer using the LCM and being dissatisfied with the assumptions on the input. Uses the extended euclid algorithm to solve the Chinese Remainder Theorem for every possible visit to a node ending in `Z` on each cycle, then finding the minimum.
code
6
u/Radiadorineitor Dec 08 '23
[Language: Dyalog APL]
6
u/Fuiste Dec 08 '23
[LANGUAGE: OCaml]
Nothing like Advent of Code to perpetually remind me how much high school math I've forgotten
Parts 1 & 2
6
u/AJMansfield_ Dec 08 '23 edited Dec 11 '23
[LANGUAGE: Fortran]
https://github.com/AJMansfield/aoc/blob/master/2023-fortran/src/08/paths.f90
Part 2 was a lot of fun to find a fast-enough numerical algorithm for. Eventually, I ended up with this:
Walk the graph until we've managed to deduce the period and phase offset for each ghost
Each pair of ghosts is combined in three steps:
I was initially worried that I would have to handle a more complicated case involving the graph having cycles containing multiple exits -- i.e. you might have a ghost that lands on the exit on the 12th and the 15th step of a 20 step cycle. Fortunately, the test didn't seem to contain any of this. (I might at some point try using GAP to write a program that does solve that case though, since I believe the native group theory operators it has would make for a rather efficient golfed solution to this much harder variant.)
6
u/xavdid Dec 10 '23
[LANGUAGE: Python]
Step-by-step explanation | full code
Using a regex to find all the 3-letter bits made parsing simple, and using
enumerate(cycle(instructions))made "how many steps have we taken in this ever-repeating list" also simple!For part 2, I did the LCM approach after doing a bit of input analysis and seeing that there were 6 distinct paths that I could solve independently (and naturally, trying the naiive solution, just in case).
5
u/seligman99 Dec 08 '23
[LANGUAGE: Python] 195 / 164
github
Hah. The longest portion of this was trying to remember
math.lcm, not exactly a normal tool in my tool bag, though it should be for AoC stuff.5
u/soylentgreenistasty Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python3]
code - rank 4233 / 967
First time ever cracking the top 1000 :)) Started with networkx but definitely didn't need it in the end.
EDIT: Cleaner version without networkx
5
u/AllanTaylor314 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python] 546/865
Code: main (c6ae21b)
Part 1: Pretty basic cycle through and follow the instruction. I was half expecting it to involve a graph traversal ("The route is too inefficient. Find the shortest path from AAA to ZZZ, ignoring the left/right instructions." - I wonder if that would make a good upping the ante)
Part 2: Stupid mistake - I was updating the original list rather than my temp
locvariable, so every iteration of the inner loop was stepping from the same spot. Withcycle, this became an infinite loop. Whoops! Found the cycle size for each starting location separately, then found the lowest common multiple. Assumes that each cycle only has one __Z in it, otherwise it would need to find all the cycle lengths that lead to Z, then find the minimum LCM of all the combinations.Future improvements: Map LR to 01 at the parsing stage and use them as indices. I could have pulled slices out of each line instead of splitting repeatedly. Make a function that contains the loop that is common between parts 1 and 2.
Edit: Made some of those improvements. Have a look at main. Want the original code? Check out commit c6ae21b
5
u/Shot_Conflict4589 Dec 08 '23
[LANGUAGE: Swift]
code
Part 1 was just brute forcing.
For part 2 I just use the LCM. Runs in about 130 ms, mainly because of the Dictionary lookups.
5
u/Abomm Dec 08 '23 edited Dec 08 '23
[Language: Python] 149 / 1831
paste
Woo! really happy with how part 1 went, I think with a little more yolo and little less double-checking and I could get top 100 for the first time.
Part 2 started with a brute force approach, that didn't go well so my instincts went to memoizing. But I implemented everything without even observing the example data and the potential for dead ends i.e. 'XXX' so I was writing all this code to get a complete map without realizing that it might be best to just focus on the start points we care about and not worry about finding paths to 'Z' where it is impossible and unnecessary.
I haven't studied the problem very carefully but I feel like input was rather generous since it seemed that following the instructions would lead you in perfect circles and not hitting Z in a sporadic manner. This made me realize that Advent is back again with the LCM! I still had some bugs in my code but patched them and plugged my findings into an online LCM calculator to get the answer, I edited my paste with the python math library and some fun set arithmetic that ultimately was not very necessary since after visiting every possible node during every possible sequence of instructions, there was only 1 way to reach Z.
I guess the takeaway for part 2 is to solve the easy problem and worry about edge cases later. Which means I shouldn't regret trying to brute-force.
5
u/voidhawk42 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Dyalog APL]
5
u/kaa-the-wise Dec 08 '23 edited Dec 10 '23
[Language: Python] one-liner/single-expression solution
No part 2, because it doesn't feel right to include a solution heavily tied to a manually-discovered input property.
https://github.com/kaathewise/aoc2023/blob/main/8.py
5
u/Cyclotheme Dec 08 '23 edited Dec 08 '23
[LANGUAGE: QuickBASIC]
Finishes in 40s at ~16MHz.
Github link
5
u/Salad-Extension Dec 08 '23 edited Dec 08 '23
[Language: C#]
Part1 was elementary.Part 2 solved by harmonizing frequencies without any fancy math.Should be understandable by beginners. Runtime roughly 15ms for both solutions.
Code
Explanatory image
5
u/Greenimba Dec 08 '23
[Language: C#]
I actually ended up solving the general case today, and it completes my input in ~60 seconds. By general case I mean:
Code
This is essentially clever bruteforcing, where instead of checking each iteration we only check valid exit indices. Runs in 1 minute, and roughly 22000x faster than brute force, so doing complete brute-force would take ~15 days.
Code is convoluted, but essentially does the following:
Follow input trail, until you get a loop.
Record all enountered Node/Instruction combinations.
Until a solution is found:
For each exit node in first loop, compute next iteration count where first loop is on exit node.
Do math to check if exit point is valid for all other loops as well:
5
u/Jorg0mel Dec 08 '23
[Language: Python]
both parts: https://github.com/Josef-Hlink/AoC/blob/main/paoc/y23/solutions/day08.py
5
u/ethansilver Dec 08 '23 edited Dec 12 '23
[LANGUAGE: Fortran]
Nothing fancy, a bit odd that for a language supposedly focused on supporting researchers, there are no GCD or LCM functions built-in. There is MOD though, so I can be grateful for that.
https://github.com/ejrsilver/adventofcode/tree/master/2023/08
5
u/POGtastic Dec 08 '23 edited Dec 08 '23
[LANGUAGE: F#]
https://github.com/mbottini/AOC2023/blob/master/Day8/Program.fs
This was the hardest challenge for me... for reasons completely unrelated to the challenge. Graph traversal is not (or at least, should not be) hard. Do you know what is? Figuring out F#'s
Seqtype.F# allows infinite data structures with
Seq, which is a natural approach here thanks to the idea of Haskell'scycle.This is fine, but the issue is that you cannot pattern match on
Seqthe same way that you can pattern match onList. Spot the O(n2) traversal here with repeated applications of this function!Whoops,
Seq.tailcreates a sequence that drops the first element. So if you callSeq.tailntimes, you still have a reference to the original sequence, but it drops the firstnelements. Repeatedly decomposing this with recursion will thus traverse the structure in O(n) for every recursive call. I spent a while snarling at why my program was getting slower and slower around 1300 elements (not nearly enough)!The solution that I arrived at was mutable state (Booooo!) and a
Seq.mapfunction that modifies the state and returnsunit. The sequence of units then gets passed to aSeq.takeWhilefunction that ignores them and instead inspects the state to see if it satisfies my predicate. I also have to fold them to force evaluation.This is awful. I am awful. What the hell, guys?
5
u/ImpossibleSav Dec 08 '23
[LANGUAGE: Python]
Here's today's one-liners! Part 1 on line 40 and Part 2 on line 66.
I was pretty happy with today's solution because I got to use a couple itertools functions —
it.cyclelike many others, but alsoit.takewhilewhich allowed me to convert mywhileloop into a one-liner. This was also my fastest solve, even despite the fact that I implemented my own least common multiple calculation before remembering the math module!Here is my updated visualization of the Basilisk, which is a single line of Python that solves all of the puzzles so far. As always, feel free to follow along with my one-line solutions on my GitHub!
5
u/red_shifter Dec 08 '23
[LANGUAGE: Python 3]
Day 8 solution (Part 1 & Part 2)
I found the LCM solution for Part 2 on this subreddit, I would never figure it out myself. But I learned something: look out for cycles in the input. I left my brute force function in the code for posterity. Someone can use it to benchmark a quantum computer in 2077.
5
u/i-eat-omelettes Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Haskell]
Both parts on GitHub
For P2: oh yes, I'm aware of equal number of A and Zs, but not that each ghost would ONLY arrive at ONE UNIQUE end node. Infuriates me so much.
5
u/sikief Dec 10 '23
[LANGUAGE: C++]
[PLATFORM: Nintendo DS (Lite)]
Solution - Part 1 and 2
5
u/mgtezak Dec 12 '23
[LANGUAGE: Python]
github part 1&2
Check out my little AoC-Fanpage:
https://aoc-puzzle-solver.streamlit.app/
:-)
4
u/davidsharick Dec 08 '23
[LANGUAGE: Python 3] 33/14
Gitlab
Never would've expected to place this high, guess that's the power of pattern recognition from doing so many puzzles; almost instantly thought of doing the LCM
4
u/bucketz76 Dec 08 '23 edited Dec 08 '23
[Language: Python]
Liked this day. Easy to understand the problem. Part 2 you have to be a bit clever since you can't simulate everything as it will take too long. The trick is to simulate each start independently until it first hits a node ending in "Z", then take the LCM of all the steps. It assumes each start hits a target node in a cyclic manner, which seems to be true.
paste
4
u/xoronth Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python], 790/442
paste
I think this is one of my highest placements, so that's cool I guess.
I wasted a bit of time wondering if I could brute force part 2 by using Cython, but then remembered the trick that I could just run them all individually and LCM the result.
It was kinda funny when I realized that as I didn't remember any of the built-in LCM functions off the top of my head, as rather than googling for LCM in Python, I instead just printed out the array and googled "LCM calculator online" and plugged it in there.
4
u/morgoth1145 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python 3] 169/71 raw solution code
Much better than yesterday!
Nothing too special about part 1, just following the sequence in the mapping until we reach the target node. (I did realize that replacing
LandRwith0and1and runningseqthroughmap(int, seq)would have been nice, but refactoring at that point would have wasted time.)Part 2 was both interesting and surprising. This is a pretty standard jumpahead problem since the ghosts need to synchronize. But what surprised me is that the answer is just the least common multiple of their first target arrival times. I fully expected that we'd need to handle either longer full cycles or shorter full cycles (or even wonky cycles where the ghosts cycle through different target values at different intervals) but the
math.lcmanswer worked! I'll likely code up a more generalized solution though so that it feels nicer :)Edit: Cleaned up code. I initially was going to code up a generalized solution but realized that it's complicated enough that I shouldn't stay up to do it now, it's already past 1AM here. Perhaps on the weekend?
4
u/Goues Dec 08 '23
[LANGUAGE: JavaScript] 655/215
Having
lcmpremadready from previous puzzles helped me a lot in part 2:4
u/KingCravenGamer Dec 08 '23
[LANGUAGE: Python] 770/481
I finally saw the trick. The trick saw me. I feel enlightened.
https://hastebin.skyra.pw/ojekuhofep.python
I did just put the cycles into an online LCM calculator as my python was in a super old version without `math.lcm` but hey.
Truly thought the LCM solution to the example was a red herring, pleasantly surprised when this actually worked.
4
u/NohusB Dec 08 '23
[LANGUAGE: Kotlin]
Repository
Part 1
Part 2
Having my pre-written utility function
leastCommonMultiplefrom previous years helped in this one!4
u/HAEC_EST_SPARTA Dec 08 '23
[LANGUAGE: Ruby]
Solution on sourcehut
Today definitely felt like one of the kindest example inputs so far this year: the additional sample for Part 2 made it abundantly clear that the node sequences were periodic, after which the next step of taking the least common multiple of the periods fell into place nicely.
4
u/xelf Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python]
Shockingly I used lcm!
and code evolution as I muck with it, current form now using a nested dictionary.
4
u/oantolin Dec 08 '23
[LANGUAGE: ngn/k]
4
u/AlexAegis Dec 08 '23
[LANGUAGE: TypeScript]
Had a hunch that doing them separately and just somehow math the numbers together will give me a result, and it did work out! I already had a least-common-multiple fn from previous years.
part1
part2
4
u/christianqchung Dec 08 '23 edited Dec 08 '23
[LANGUAGE: C++]
Part 1 (#1918):
Simulated using a map of a string to a pair of strings. Not very noteworthy.
Part 2 (#6387):
Believe it or not I was on track to be top 2000 since I realized it was an LCM problem a few minutes in. Unfortunately, I calculated the path cycle wrong, leading me to do waste half an hour doing a more efficient simulation that would've taken too long to get to the actual answer. The whole time I had a wikipedia about LCM open too which makes it even worse.
Video upload soon.
4
u/Error-0221 Dec 08 '23
[LANGUAGE: Elixir]
Solution
It must be said that daily reading comprehension is the real challenge.
4
u/SuperSmurfen Dec 08 '23 edited Dec 08 '23
[Language: Rust]
Link to full solution
Really fun problem today! Both a simple graph problem and some number theory. For part you just simulate the graph traversal:
For part two you just compute the same thing but for all ghosts. Then you compute the least common multiple of all those steps
4
u/flwyd Dec 08 '23
[Language: Julia] ((on GitHub)
[ALLEZ CUISINE!] Every variable and function that I can change is now an emoji. (If you want an emoji-free version, see the link above.)
Part 1 took me 10 minutes, and I was going at a casual pace. Part 2 took an additional 50 minutes because I figured I'd let my Pluto notebook keep churning away at the naïve solution while I worked out the smart solution in vim. But I had some copy/paste errors and had to fix my part1 to work on the third example input so the program didn't crash until I got to part 2. My first wrong answer used a product of all the recurrences (steps-to-first-Z), which looked suspiciously high: between 263 and 264. I was pretty sure AoC numeric answers will always integers that can be precisely represented by a 64 bit floating point number, but it took me a minute to realize I wanted
lcm(least common multiple) and not the actual product.4
u/bld-googler Dec 08 '23
[LANGUAGE: Julia]
I was unsatisfied with today's problem, so I wrote some prose talking through the reasons that the shape of the input made my specific approach work.
I was a bit dissatisfied with this puzzle, not understanding why I got the right answer. So I looked into it more to explain it.
https://www.mattwest.org/uploads/2023/day08.html
4
u/Naturage Dec 08 '23
[Language: R]
Solution here. If you're worried at all about spoilers, first of all, why are you here, but secondly, skip the below.
This was actually very fun, on par for expected difficulty, and had the AoC twist I hoped for. My one complaint is that the problem sets you up for a much, much harder part 2, and then gives you a very specific, easy case input. I'd want to see a return of this around day 20 or so with a different, nastier input (after reaching Z, doesn't go back to corresponding A. Reaches Z not at end of directions, so next time you turn the other way at same spot. Reaches multiple Z per loop. Reaches same Z multiple times per loop but at different bit of directions.)
Also, I found out that R does not have an in-build gcd/lcm function, so off to type one I went.
4
u/[deleted] Dec 08 '23
[Language: TypeScript]
Part 1 - 576.91 µs
Part 2 - 2.31 ms
4
u/thousandsongs Dec 08 '23
[Language: Haskell, but in Hindi] [Allez Cuisine!]
Hindi is the third most spoken language in the world, every 1 in 10 people in the world speak it. But I doubt your knowledge of Hindi will help you understand this code. But that's fine, the Haskell compiler understands it – this 505 character punch card solves today's problem in 0.5s.
The characters used are from the देवनागरी (Devanagari) script that is used to write Hindi.
my actual readable solution is here
EDIT: BTW, if you have any tips on how to golf this further, please do say!
4
u/[deleted] Dec 08 '23
[LANGUAGE: Forth]
Part 1 was easy enough to implement, and I went with the LCM for part 2. You can control the numerical base Forth operates in with its
BASEvariable; setting that to 36 made parsing the input network a piece of cake.https://github.com/tcsullivan/advent-of-code/blob/master/day8/partboth.fth
4
u/muthm59 Dec 08 '23
[LANGUAGE: Perl]
Nice puzzle! Part One is quite simple with a node hash containing the left and right next nodes, and moving through the instruction string using the step counter modulo the instruction length:
For Part 2, I did a loop detection for each 'A' track. I store the step count for each time I encounter the 'Z' node (in
@seen_Z).I've seen the possiblilty that starting from the A node, we go through a number of other nodes before we enter the loop, kind of 'phasing in'. This would make loop calculations much more difficult! To verify that this is not the case, I ran until Z was visited twice, not only once. We are good if the number of steps for A to Z and the number of steps in the loop (from Z to Z) are the same, and they actually are! This also means that the first node after any A node is the same as the one after the corresponding Z node.
But then it came to me that there's no guarantee for that, because the path after reaching the Z node depends on where we are in the L/R instructions! So it could be possible that after Z, we go a completely different way, and not loop at all, or in different loops!
I tried to find out why this works, why we are getting nice loops even considering the unpredictablity of the L/R instructions. It turns out that the number of L/R instruction is a divisor of all loop periods that I found! Every loop has a period that is an integer multiple of the number of L/R instructions given!
I really admire the great job done for setting up the input data!!
My complete solutions including run scripts on GitLab
4
u/TheZigerionScammer Dec 08 '23
[LANGUAGE: Python]
Ahh, the first problem where we have to come up with a clever solution to get the problem to run in a reasonable time. Part 1 took 10 minutes, I just coded what the problem told us to simulate, nothing special there. Part 2 was where it got interesting. I modified the program to run all the ghost simultaneously, which "worked" but of course never finished. So I modified it again to record when each ghost came across a Z space and to stop that ghost when it comes acorss the same Z space on the same point in the left-right cycle. I was expecting that each ghost might move over multiple Z spaces and we'd have to figure out which part in the cycle they all converge, but no. Actually looking at the record showed the ghosts never came across more than one Z space and they always entered their own Z space at the same point in the cycle.
Ok, so once I had that data I tried to program a separate simulation. The way it worked is it took each ghost's cycle count, added it's differential if it was the ghost with the lowest cycles, and compared them to see if they were all the same. This of course never finished either. So I decided to look at the numbers themselves, and while the differentials were all divisible by the length of the string as I expected, I also noticed that the ghosts' current cycle count was exactly double the differential, which means there's no modular math shenanigans going on, I just need to lowest common multiple of these numbers. I could have programmed that more robustly but after confirming that the differential divided by the string lengths were all prime, I multiplied those numbers all together and multiplied by the string length again. That worked.
Code
4
u/jaccarmac Dec 08 '23 edited Dec 08 '23
[LANGUAGE: LFE]
code
Writing math functions in Erlang/LFE can be very pleasant.
4
u/RelativeLead5 Dec 08 '23 edited Dec 08 '23
[Language: Ruby]
4
u/DrunkHacker Dec 08 '23
[LANGUAGE: Python]
4
u/crazy0750 Dec 08 '23
[LANGUAGE: Rust]
This time, the brute force for part 2 didn't finish before the proper solution :)
For part 1, I used Hashmap to store the nodes and paths.
Used the num crate to calculate the lcm in part 2, after finding the position where each start would "finish".
code
4
u/Comprehensive_Ad3095 Dec 08 '23
[Language: Lua]
Part 1: Easy, i used maps with keys as values.
Part 2: Interesting, Im not sure but I used LCM from all minimum count to "z" to solve quickly.
Github
4
u/clbrri Dec 08 '23 edited Dec 08 '23
[LANGUAGE: C-style C++]
Did both a LCM based solution and a proper scanning solution that does not assume that there is just one goal inside each cycle. The scanning solution finishes in less than a second on my PC. Code
4
u/ruinedme_ Dec 08 '23
[Language: Rust]
Once i figured out that the move sequence length is a prime number and all starting locations will be some multiple of that prime it was a simple matter of figuring out the LCM of each of the starting locations.
https://github.com/ruinedme/aoc_2023/blob/main/src/day8.rs
4
u/biggy-smith Dec 08 '23
[LANGUAGE: C++]
ah my old enemies, lcm and size_t!
https://github.com/biggysmith/advent_of_code_2023/blob/master/src/day08/day8.cpp
4
u/kbielefe Dec 08 '23
[LANGUAGE: Scala] GitHub
Part 1 just followed the instructions. Part 2 took the LCM of all the path lengths.
4
u/Polaric_Spiral Dec 08 '23
[LANGUAGE: Typescript]
Advent of Node, Day 8
lcm implementation based on Euclidean algorithm
I have mixed feelings on part 2. I spent a while trying and failing to come up with a solution that worked in the general case and ran in a workable amount of time. I set up something I thought was sophisticated, but was still too brute-forcey for this one.
I eventually examined the "ghosts" and realized that they always hit the "Z" nodes at the end of the left-right instruction list. This isn't even true for the example input. Not only that, but each ghost only hits one "Z" node at a set cycle length with no offset from the start of the puzzle.
I implemented a basic LCM solution (I already had the algorithm ready) and satisfied myself with some checks so that the solution would throw an error if given some input that didn't follow those rules.
4
u/vss2sn Dec 08 '23
[LANGUAGE: C++]
Part 1
Part 2
(Each file is a self-contained solution)
4
u/Tipa16384 Dec 09 '23
[LANGUAGE: Python]
I couldn't get the Tortoise/Hare algorithm working, so... LCM like everyone else I guess.
4
u/manhuntos Dec 19 '23
[Language: Rust]
This is my first project in rust. I'm learning it by solving advent of code puzzles. So if you have any hints for me I would be happy to read it :)
Solution / 648.68µs / 26.23ms
1
u/Portlant Dec 08 '23
[LANGUAGE: Tcl]
fun part 1
https://topaz.github.io/paste/#XQAAAQBIAgAAAAAAAAA5mUrqJXcsU7QQwAHwF/EC7gc9DcSanro/JiAs8Ht/jcAvojV8xQnl6MN4uIMHzCU2JvD9A3hMTVCtqFDK9jBahWdMtywSHdTQBLg+ffzmTizKEr2FoRZ1z+KFl48CjAV6dryrFrUg9lhYNQLdwI24ORtw4+vdmMUgTD7df8gnUn3NwjPHdUyU17YbqzJuSha1wT+9lwAq47Zs1R/wo6P6jT6Idw6M94OJWXx91EqzTlkMUYdEioeweR43N69Befp9j8vIC8oBLqSN4CRofgBZy7GGINhNdFo5oxpm+UNwyYwIB1SMbve8DIabzBtq71VDHQBKbBXQPUM0yl4pnO5Xa9Rt360shmh9A7h/bbdRfC9fLLuxDRqY7c13hfU5Bui2EZYsVtDuswrX+WzOT9RfEjDh6O+DLwf9sZUJHJYWrjseCKc+ZRyvfcU1UXXA/iEF/7goZS4=
1
u/sjhunt93 Dec 08 '23
[LANGUAGE: python]
Like others I tried to brute force. LCM is the way:
1
u/[deleted] Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Clojure]
Wrote a quick and dirty LCM calculator for part 2. I could have used a Java interop for the GCD but yolo.
1
u/[deleted] Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python]
The second part was hard using dictionaries and for loops until I realized that it was about Least Common Multiple or LCM. The only thing you have to do is to get the target node for all nodes that ends with
"A". Then just get the steps for those pairs of nodes. Finally, just get the LCM of those values and done.This works because the puzzle input is like an automaton. So, you have to advance N steps to reach the node with the maximum steps at the first iteration.
Sample Image
Here you have the code: https://github.com/crixodia/aoc/tree/main/2023/08_haunted_wasteland
1
u/levital Dec 08 '23 edited Dec 08 '23
[Language: Haskell]
I liked this one, and occasionally felt clever here (like parsing L/R to fst/snd). Tried brute-forcing part 2 at first on the off-chance that it works (it doesn't, though it might have if I hadn't constructed the entire paths in memory, not sure whether ghc optimizes that out). Quickly realized while the brute-force was running in the background that it would be an LCM solution, but I thought at first that this would mean I need to find cycle-lengths for every possible end-node and a respective initial point where the cycle starts (there's no guarantee, after all, that they all go back to the start). Fortunately the input was nice and just finding start node -> unique target node was enough.
Does it count as Allez Cuisine, if english is a foreign language for me? ;)
Edit: Of course the latter line was in jest, but here's a proper [Allez Cuisine!]: A rather questionable German translation. This feels appropriately cursed to me, even though I didn't have an idea how to replace language keywords. Thankfully Haskell doesn't have that many.
1
u/kenlies Dec 08 '23
[LANGUAGE: C++]
Had a slip up on part 1 with thinking that the first line is always the starting position whilst the last line is where we need to end up with. Consequently smashed my head against a wall for far too long.
https://github.com/kenlies/Advent_of_Code_2023/tree/main/day8
1
u/m44rt3np44uw Dec 08 '23
[LANGUAGE: PHP]
I did brute force part 1 and tried to do the same thing for part 2. It took me a peak at the subreddit to realize I had to use `gmp_lcm` to solve part 2.
To solve both part I did use a do while loop and an infinite iterator. Those are some things I don't usually use during my day-to-day job.
GitHub Gist
1
u/mtpink1 Dec 08 '23
[LANGUAGE: Python]
Code: github
Part 1 was very straightforward with simply loading the graph into a dictionary and traversing until you hit
ZZZ. For part 2, my intuition was that it had to have something to do with finding where the cycles aligned, but I was initially off put by the complexity.Upon doing some exploration of the actual data I found that the cycles were all divisible by the length of the directions and we not offset within the directions (e.g. you could imagine that a cycle would be of the same length as the directions but not start and end at the start of the directions, which would make things much much more complicated). From there all it took was a quick search to find the
math.lcmfunction and I was done.If anyone's interested, I've also been recording myself while solving the daily problems at my youtube channel! I'm not an expert programmer by any means, but I think that showing my full thought process could still be helpful to others.
EDIT: formatting
1
u/Nikla436 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: JavaScript]
This was a fun one today. Very pleased with how my solution came out. Tried brute force at first which worked for part 1.. and part 2 forced me to rethink the problem.
3
u/mebeim Dec 08 '23 edited Dec 09 '23
[LANGUAGE: Python 3]
285/152 — Solution — Walkthrough
Nice and easy problem. For part 2 you can try every single path individually and then compute the least common multiple of the steps needed by each path to find out after how many steps all converge to a node ending in
Z. EDIT: or so I thought... if you think about it for more than 5 minutes this should not work in general. Turns out we all were pretty lucky that the inputs were constructed in such a way that made LCM (and the assumptions around it) work. MEH.Busy day today, going back to sleep zzZZZ. Clean solution and walkthrough here later today (hopefully). EDIT: cleaned the solution and added walkthrough!
3
u/maths222 Dec 08 '23
[LANGUAGE: Ruby] 749 / 183
As soon as my naive part 2 kept running for more than a few seconds I figured I needed to use LCM. Conveniently, ruby's standard library has a LCM function sitting right there for the taking (though if you had asked me that before tonight I wouldn't have known :) ).
code
3
u/770grappenmaker Dec 08 '23
[LANGUAGE: Kotlin] Placed #74/#147 today, overall pretty happy with what I ended up with.
3
u/Frajd Dec 08 '23
[LANGUAGE: C++17] 918/479
repo-folder
This was my first attempt at the leaderboard. I couldn't sleep, so I gave it a go.
As others mentioned, I was surprised that a standard LCM answer was correct on the first try. That was a welcome surprise. I was sure you would likely have to track different types of cycles across nodes.
3
u/cetttbycettt Dec 08 '23
[Language: R]
For part 2 I considered the starting points one after another until the reach a node ending in 'Z'. Then I took the least common multiple.
3
u/FCBStar-of-the-South Dec 08 '23
[LANGUAGE: python3]
Also tried to simulate part 2 at first. The cyclic directions led me to guess that each start -> end sequence cycles with a fixed length. Seems to hold.
3
u/ranikola Dec 08 '23
[Language: JavaScript] Code
For 2nd part trick was to stop each search when Z is found and then use LCM.
3
u/Horsdudoc Dec 08 '23
[LANGUAGE: C++20] 1560/800
File on GitHub
Trusty std::lcm to the rescue. As many mentionned, I was afraid there would be more than one possible cycle to check for each starting position.
3
u/wace001 Dec 08 '23
[LANGUAGE: Kotlin]
Took me 5 minutes to realise that I had instructions, I was planning on doing BFS/DFS on part one.
For part two, I just took a shot, I guessed it was repeating and I could just go LCM. Worked fine! Fun day!
Kotlin solution
3
u/UseUnlucky3830 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Julia]
[GitHub]
Nice that we could re-use the Part One solution to help with Part Two. Having been fooled by an LCM problem last year already, I just guessed that something must repeat periodically and checked.
3
u/maneatingape Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Rust]
Rust Solution
Part two uses the combined LCM of each individual path.
EDIT: Sped things up about 10x by converting each node name from a string to a unique index. Then could use twovecs and jump around from index to index instead of needing a hash lookup.EDIT 2: Using the fantastic visualization here enables a really neat insight - we don't need to care about the directions at all!
If we find the length of each smaller graph cycle (using a BFS for example), then find the LCM of that with the length of the directions then we find the period of each cycle ending with
Z.The part two answer is then the combined LCM of those LCMs. My solution now completes in only 34 μs.
3
u/Any-Razzmatazz-4792 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Ruby]
Didn't consider LCM for a while, once I pieced that together I was able to put together a solution. Here's some golfed code for shits and giggles though
Part 1:
Part 2:
3
u/SymmetryManagement Dec 08 '23
[LANGUAGE: java]
https://github.com/linl33/adventofcode/blob/year2023/year2023/src/main/java/dev/linl33/adventofcode/year2023/Day8.java
The cycle pattern for this puzzle is surprisingly simple. I am coming back later to optimize away the
HashMap.3
u/Boojum Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python] 1011/3630
Oh, I guess it's that one. Time for the annual cycle finding problem again. :-)
3
u/MiserableOrdinary113 Dec 08 '23
[LANGUAGE: Java] 1342/1311
github
3
u/s3aker Dec 08 '23
[LANGUAGE: Raku]
solution
3
u/Biggergig Dec 08 '23
[LANGUAGE: Python3]
Video Walkthrough Code
Bit unsatisfying due to the assumptions I made in order to keep the code simple, but I think those assumptions are necessary for this to be a day 8 problem. Pretty happy with my use of `yield from`, and I now learned python3.9+ has a builtin lcm function in the math library!
44ms for both parts on my machine
3
u/aashutoshr Dec 08 '23
[LANGUAGE: JavaScript]
Pastes
3
u/janek37 Dec 08 '23
[LANGUAGE: Python]
I was afraid that I was going to use CRT, but then I've checked that for each ghost, the only Z position is at the end of their period, so LCM works as well and is much simpler.
GitHub
3
u/TeakIvy Dec 08 '23
[LANGUAGE: Java]
I definitely over-engineered this, but it works (and quite fast at that).
For part 2 I used LCM, based on other comments I'm not sure if this would work for all inputs, but seems to work for at least most
GitHub
3
u/sim642 Dec 08 '23
[LANGUAGE: Scala]
On GitHub.
The stepping simulation was very convenient using my
.cycleand.scanLeft.In part 2, I take the LCM of individual ghost step counts which makes a bunch of assumptions that luckily happen to hold here. I wasted time thinking I needed a more general solution because my first answer was too low, but that was only because
Intoverflowed.3
u/sansskill Dec 08 '23
[LANGUAGE: Kotlin]
https://github.com/sansskill/adventofkode2023/blob/main/src/main/kotlin/days/D08.kt
After brute force obviously didn't work for part2 I figured I'd output for every location how long it takes to find the first Z location and then how long it takes to loop and at what point in between it finds other Z locations. Realized then that every start location only visits one end location and the time to first end location was equivelant to the loop time. Was quick solve after that.
3
u/Constant_Hedgehog_31 Dec 08 '23
[Language: C++]
Source code in GitHub.
Part two: first, without much hope it'd finish, I tried with the naive approach moving from all nodes simultaneously and checking if we've arrived at nodes that end in Z altogether. When it wasn't finishing, I realized that there were only a handful of starting nodes, so I run the simulation from each node individually and compute the least common multiple of the number of steps using Python as a calculator.
3
u/ri7chy Dec 08 '23
[LANGUAGE: Python] Code
It reminds me of Day12 in year 2019 - The N-Body Problem - no spoilers.
Nevertheless: Is there a one-liner to create this dictionary?
3
u/vu47 Dec 08 '23
[LANGUAGE: Kotlin, functional programming]
This was one of the puzzles I've enjoyed most this year. The use of the lcm to solve part 2 was a nice touch.
paste
3
u/ondrsh Dec 08 '23
[LANGUAGE: Kotlin]
Missed the part that said we start at "AAA". I just picked the first one. Of course both examples have "AAA" as the first nodes so everything worked out fine. My reading comprehension is so bad it's comical.
Simple straightforward solution, runs everything in 2.7ms on one thread. If you add async{} and then awaitAll() it runs in 0.66ms.
https://github.com/ondrsh/AdventOfCode2023/blob/master/src/main/kotlin/Day8.kt
3
u/[deleted] Dec 08 '23
[LANGUAGE: Google Sheets]
Assuming the input is in A:A
Part 1
3
u/Short-Leg3369 Dec 08 '23
[LANGUAGE: PYTHON]
https://github.com/p3rki3/AoC2023/blob/main/Day8_solution.py
Part 1 relatively straightforward.
Part 2 - well I could have let a part1 style program run all day, but thats no fun, so looked for a quicker solution. Printed the stepcounts for the first 5 potential exits of each startpoint, saw the simple pattern, and then coded a quick lowest common multiple solution.
Total runtime : c30ms for both parts
3
u/busseroverflow Dec 08 '23
[LANGUAGE: Go]
The code is on Github.
Implemented an LCM function myself, since the Go standard library doesn't provide one. I had to open up the Wikipedia page to remember how (high school was a long time ago 😅), and was really surprised at how simple it is.
3
u/jeis93 Dec 08 '23
[LANGUAGE: TypeScript]
Parsing the input and finding the solution for part 1 was pretty straight forward. Going into part 2, I knew I couldn't run it the way that first popped into my mind. I'm no math guy, but I knew I needed to find the fewest steps from each starting node and figure out when they'd all overlap to ensure the code didn't take years to run (this is LCM). Shout out to u/AlexAegis for providing a solution (and math library) that pushed me in the right direction! Let me know what you think. Happy hacking!
Average times:
TypeScript x Bun Solutions for Day 8 (Parts 1 & 2)
3
u/fotosjopjes_ig Dec 08 '23 edited Dec 08 '23
[LANGUAGE: JavaScript]
Kinda proud of the way how I've made both parts work with the same function.
https://github.com/mark-boots/Advent-of-Code/blob/main/2023/day8/index.js
3
u/Salabeaver Dec 08 '23
[LANGUAGE: Python]
3
u/A-Marko Dec 08 '23 edited Dec 08 '23
[Language: Uiua 0.6.1]
I didn't realise that AoC has hidden properties of their input data sometimes. I'll have to keep that in mind for the future. My brute force was taking too long, so I had a peek at the subreddit. Link
3
u/Chivalric75 Dec 08 '23
[Language: Python]
This was a great puzzle to learn the use of generators.
paste
3
u/dehan-jl Dec 08 '23 edited Dec 08 '23
[Language: Rust]
Code (GitHub) - 60 Sloc
Tried brute-force, realised there were probably cycles, tried LCM, worked.
Edit: got it down from ±16ms to ±2ms runtime by storing my steps in a vector, not a String.
Part 1 and Part 2 are basically the same anyway ¯_(ツ)_/¯
3
u/PatolomaioFalagi Dec 08 '23
[Language: Haskell]
Part 1:
Part 2:
3
u/SpaceHonk Dec 08 '23
[Language: Swift] (code)
Part 1 is a simple walk through a dictionary of nodes, all alike.
Reading part 2 I quickly realized that brute-force wasn't going to cut it, so on a hunch, I tried LCM like apparently everybody else, and hurray! it worked :-)
3
u/_drftgy Dec 08 '23
[LANGUAGE: Elixir]
Solution
My solution for second part initially was to run all paths in parallel (that's why there are calls to
Task.async/awaitthere) until number of steps for each step becomes equal. One iteration of that took around 10ms. After getting the actual solution, decided to calculate how long this approach will take, and found out it would be about 4000 years 😅.3
u/zniperr Dec 08 '23
[LANGUAGE: Python]
3
u/Fyvaproldje Dec 08 '23
[LANGUAGE: Raku] [Allez Cuisine!]
https://github.com/DarthGandalf/advent-of-code/blob/master/2023/День08.rakumod
For part 2 find the paths for every ghost separately, and take LCM of them
3
u/plusminus1 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: C#]
Part two took a while before I had a eureka moment. The clue is as always in the data itself...
(full code here: paste )
3
u/sgxxx Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python]
9 lines with imports.
https://github.com/sayan01/advent-of-code-2023/blob/master/08/p.py
TIL about itertools.cycle, count, and creating infinite generators using iter(int,1). Trying to learn a new thing every day.
3
u/Jessseee Dec 08 '23
[LANGUAGE: Python]
I quite like this solution. I know it is probably more efficient to only loop through the instructions once, but I like that I can use the part one function to solve part two as well.
Also on GitHub.
3
u/Exact_Apple_9826 Dec 08 '23
[LANGUAGE: PHP]
https://github.com/mikedodd/AdventOfCode2023/tree/main/day_8
after brute forcing part 2 for 20 mins I was confused, I reduced the number of start nodes for 6 to 2 and it worked, could just about calculate 3 start nodes so then I realised Brute force was not the answer, once again Part 1 leading me down a wrong path. I love it!
I needed help to realise it was a LCM solution as I assumed there was a fault in my logic... thanks to this thread I realised It was a LCM solution.
3
u/jcmoyer Dec 08 '23
[LANGUAGE: Ada]
https://github.com/jcmoyer/puzzles/blob/master/AdventOfCode2023/src/day08.adb
Similar problems in prior years so deciding to use lcm was pretty straightforward. Though honestly I yolo'd it after seeing each start had exactly one reachable exit and submitted lcm(d0, d1, d2, ...) before checking if the paths actually cycled.
3
u/fachammer Dec 08 '23
[LANGUAGE: Scala] github
Assumed that all the paths from start nodes have exactly one end node and that the cycle length from a start node to its end node equals the cycle length from end node to itself regardless of where we start in the step sequence. Also added assertions for these assumptions in the code. Then I took lowest common multiple of all the cycle lengths to get a result that works for the input (which satisfies these assumptions)
3
u/G_de_Volpiano Dec 08 '23
[LANGUAGE: Haskell]
Today was much more difficult for me than it should have been. First I skipped the part about the instructions, so got absolutely irrelevant results on the test cases. Took me a long time to understand why.
Then I wasn't sure, from the instructions, whether we could encounter a goal only at the end of a set of instructions or at any step, so I assumed the worst. Ran OK for part 1.
When my implementation for part two hadn't given any answer after five minutes, I decided that this might be the problem. Reimplemented everything assuming that we only could end up on a goal after going through a whole set of instructions (which, at least in my case, turned out to be true), so I redesigned my node map. Still no answer after going on for minutes. So that's not the problem.
So I went full nuclear. Let's apply Floyd-Warshall on the graph and see what gives. My first idea was to look for paths in that new map from any start node to any end node. Luckily for me, I first checked what the available ('A' ending, 'Z' ending) edges where. Turns out each 'A' ending node is only connected to one 'Z' ending node. Once I had that, the answer was straightforward. Take the lowest common multiple between the edges weights, and voilà.
Still took 15s to run (it's a huge graph to run Floyd-Warshall on), so I went back to my initial hunch. As I actually new there was only one goal possible per start node, I ran a breadth-first search on each start node to find the closest (and actually sole) end node, then same lowest common multiples, and a decent performance.
Part 1. CPU Time:0.0056s
Part 2. CPU Time:0.0129s
https://github.com/GuillaumedeVolpiano/adventOfCode/blob/master/2023/days/Day8.hs
3
u/Markavian Dec 08 '23
[LANGUAGE: JavaScript]
https://github.com/johnbeech/advent-of-code-2023/blob/main/solutions/day8/solution.js https://github.com/johnbeech/advent-of-code-2023/blob/main/solutions/day8/distance-map.json
Ugh. Part 2. You know what tripped me up and caused me to get into an unsolvable infinite loop?
I read this as needing to go Left and Right paths at the same time... which was reinforced by the example - so I ended up hardcoding a direction list of ['L', 'R'] instead of using my input directions... and if you follow LR on repeat... guess what? You never find ..Z nodes.
3
u/SnooPandas3374 Dec 08 '23
[LANGUAGE: Python]
Part1
Part2
3
u/FlockOnFire Dec 08 '23
[LANGUAGE: Elixir]
https://github.com/janssen-io/AdventOfCode/blob/main/Elixir/lib/2023/08.ex
3
u/qoqosz Dec 08 '23
[Language: Rust]
Day8 in Rust
Today was a good day to test iterators.
3
u/No-Monk8319 Dec 08 '23
[LANGUAGE: Rust]
https://github.com/NikolaIliev/aoc_rust/blob/master/src/bin/year2023_day08.rs
~100-400µs solutions for both parts (M1 Max). Storing nodes in sequential memory (Vec) was the key to achieving sub-1ms. ~900µs even without par_iter!
3
u/mrvoid15 Dec 08 '23
[Language: Golang]
https://github.com/akashdeepnandi/advent-of-code/blob/main/day8/main.go
For part 2, uses LCM formula - LCM(a,b) * GCD(a,b) = a *b
3
u/Pretty_Yak3622 Dec 08 '23 edited Dec 08 '23
[Language: Rust]
Part 2: https://pastebin.com/SSQizNfY
I'm learning rust during this year's AoC, and I enjoyed today's challenge as it mapped nicely to a simple, mostly functional, approach.
3
u/CowImaginary3155 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: PowerShell]
Part1:
3
u/Singing-In-The-Storm Dec 08 '23
[LANGUAGE: JavaScript]
Parts 1 & 2 (under 33ms each)
code on github
3
u/mathsaey Dec 08 '23
[Language: Elixir] https://github.com/mathsaey/adventofcode/blob/master/lib/2023/8.ex
I like puzzles like today; a fun little challenge without getting into frustrating territory.
I first didn't see the paths at the top of the input and thought that this would be a pathfinding problem; I was thus very confused about the "repeating paths" paragraph of part 1. Lost a bit of time before I realized that the problem was easier than I thought and that I just made a stupid mistake.
Part one was very easy, I tried brute-forcing part two first until I decided to just use the lcm. Ended up with what I consider to be nice, compact code in the end :).
3
u/rawlexander Dec 08 '23 edited Dec 08 '23
[LANGUAGE: julia]
Repo
3
u/mulokisch Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Elixir]
https://gist.github.com/adrian-goe/d49a2d6b35d5e794a7aaf9ed5668cc4a
If you want, give me feedback
3
u/ZeroTerabytes Dec 08 '23
[LANGUAGE: Python3]
https://github.com/racecraftr/adv_of_code/blob/main/y2023/day8/day8.py
This was...actually easy? Wtf
3
u/[deleted] Dec 08 '23
[Language: Python]
https://github.com/spikedoanz/advent-of-code/blob/main/2023/day8.py
Saw a tree like structure and nearly had a heart attack. Didn't expect them to just outright give us the path to the end node :D
3
u/Rodbourn Dec 08 '23
[LANGUAGE: C#]
https://github.com/Rodbourn/adventofcode/blob/main/Day008.cs
I think they did everyone a favor in part 2 by showing you visually how the first took two steps and the second took three, and the final answer was six. That was basically hitting you with a least common multiple ruler on the wrist when you thought about brute forcing it.
My final answer was in the dozens of trillions... so it might not be worth brute forcing :)
My overall runtime was 25 ms, doing both parts at once.
To lay it out... part 2 was just like part 1... small tweak on the ending condition... but you do it on all the matching start values and collect the answers. Then just compute the least common multiple of those numbers and you are done.
3
u/ManaTee1103 Dec 08 '23
[LANGUAGE: Python]
Yay for adding lcm to Python!
3
u/ForScale Dec 08 '23
[LANGUAGE: JavaScript]
Part 1
3
u/matheusstutzel Dec 08 '23
[Language: Python]
Part 1 straightforward implementation. Treat it as a graph and just follow the instructions.
Part 2 for each start point, run the part1 code and save the result. The answer will be lcm (least common multiple) of them
3
u/s4uull Dec 08 '23
[LANGUAGE: Nim]
Today was reeeally cool :-00 I didn't know about the chinese remainder theorem and it blew my mind!!
I solved it using the LCM. Nice puzzle!
link
3
u/Withered_Flower__ Dec 08 '23
[Language: MiniScript]
Code: https://github.com/Withered-Flower-0422/AoC-2023-MiniScript/tree/main/day8
3
u/Backwards_Reddit Dec 08 '23
[LANGUAGE: Rust]
https://github.com/RansomTime/aoc2023/blob/main/day_8/src/main.rs
I realised that the periods were the same, but not that the first loop of the periods was the same as the period length.
So first run of this was a lot more code that ended up solving in over 60 seconds as it was basically just looping through every possible permutation of the loop.
Once I realised that the period was the same as the first iteration of the loop, I made it LCD and that worked much faster.
3
u/jitwit Dec 08 '23 edited Dec 08 '23
[Language: Scheme]
I usually solve in J, but for problems like this I feel like scheme's flexibility makes it easier to write solutions.
https://github.com/jitwit/aoc/blob/a/scheme/23/08.ss
Actually, it solves quite nicely in J:
3
u/Brief-Presentation-4 Dec 08 '23
[LANGUAGE: C#]
solution
3
u/jordibeen Dec 08 '23
[Language: Rust]
using AOC to learn more about Rust's iteration tools, pretty happy with how this one turned out
link
3
u/brtastic Dec 08 '23
[Language: Perl]
Github
Part 1 completes in 9ms, part 2 in 38 ms. LCM is not in Perl (unless you use BigInts), so I used a module for that. Surprisingly, BigInt solution runs just as fast.
3
u/Paulradjr Dec 08 '23
[Language: Python]
3
u/plant_magnet Dec 08 '23
[LANGUAGE: R]
https://github.com/ddavis3739/advent_of_code/blob/main/2023/08/code/08.r
>! While loops and LCMs
3
u/Imaginary_Age_4072 Dec 08 '23
[LANGUAGE: Common Lisp] 4989 / 5949
Day 8
I had fun with this one. The first part I got fairly easily and like most here it was just an iteration through the list of directions.
The code in the link above is tidied up and just solves the problem with
lcmfor part 2, but isn't how I originally found the solution.I initially tried a brute force solution to part 2, since I was worried about the complications of all the different ending points and that the cycles could take some time to start, but gave that up after it ran for a couple of minutes without finding anything.
Common Lisp has a great REPL though so I spent a bit of time just exploring the data. I thought it might be cycles, so wrote some code to find how long it took to repeat a (location direction-index) pair and the length of the cycle for each starting index:
I wanted to look at the cycles themselves, so had a look at the ending and starting of the first cycle:
I was playing around with the cycle, because I thought the first instance of getting to
:ZZZwould take longer so just tried some things out:But then suspiciously saw that it perfectly repeated.
And I also remembered that I had seen that number from the list that I first got when looking at cycle lengths, so just passed all the lengths to
lcmand got the answer.Even though it wasn't my fastest time, I really liked this puzzle.
3
u/CCC_037 Dec 08 '23
[Language: Rockstar]
Simple, straightforward, in part 1. Follow the path until the end.
3
u/SwampThingTom Dec 08 '23
[LANGUAGE: Rust]
Started by brute forcing part 2 but figured that wouldn't work. While it was running, I implemented a quick-and-dirty recursive gcd function, since Rust doesn't have one in its standard math functions and I'm not using crates. About the time I had that working on the sample input, the brute force solution OOM'd. :-)
Github
3
u/ropecrawler Dec 08 '23
[LANGUAGE: Rust]
I tried to find a solution for the general case but couldn't. LCM obviously doesn't work, but I can quickly come up with examples that CRT won't easily solve either. So, I gave up and Made All The Assumptions:
https://github.com/ropewalker/advent_of_code_2023/blob/master/src/day08.rs
3
u/Ok-yea-sure Dec 08 '23
[Language: JavaScript]
I was able to solve part 1 without a problem then realized after trying to brute force part 2 that there must be a trick that I was missing (because my script never stopped running). Had to use a hint on reddit for the LCM solution unfortunately. I really don't know how anybody can just intuitively think to use LCM off the top of their head for a problem like this... pattern recognition I guess? Anywho, you live and you learn.
Part 1
Part 2
3
u/Chris97b Dec 08 '23
[LANGUAGE: C++]
Took me a bit to figure out the trick, but honestly this wasn't bad once I wrapped my brain around the math in Part 2
Git
3
u/mothibault Dec 08 '23 edited Dec 17 '23
[LANGUAGE: JavaScript]
https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day08.js
with tons of in-line comments
3
u/dommmyrock Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Rust ]
Part 2 - Elapsed 11.8126ms (-release)
Using mostly fn chaining and 'num' crate's lcm helper func
https://github.com/dommyrock/aoc/blob/main/aoc_2023/day-08/src/bin/part2.rs
3
u/hugseverycat Dec 08 '23
[Language: Python]
For part 2 I did what I assume many did; calculated the steps for each ghost to the nearest Z, and then got the least common multiple. I don't know why it works and I'm looking forward to reading the proof!
Anyway, here's my code. Tried to make it pretty readable, with comments:
https://github.com/hugseverycat/aoc2023/blob/master/day08.py
3
u/ywgdana Dec 08 '23
[LANGUAGE: C#]
Solution on github
When I began to read the problem I was like "Oh no I'm not emotionally ready for pathfinding yet!" but was pleased to see it was much simpler than that. I was also pleased that my guess for part 2 that each ghost was going to move in a cycle was correct and that I could just find the LCM of various paths.
For me, this was the perfect level of difficulty in that it required just enough brain power to make me feel a bit smart :P
3
u/lMoonhawk Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python]
Why use LCM? If you go as far as assuming steps(XXA,XXZ) = steps(XXZ,XXZ), why not also assume each cycle divided by the length of the instruction are coprime? I have a more general part 2 that uses CRT.
3
u/Due_Scar_5134 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: JavaScript]. Assumes that the input file is read into a string[]Had to look up how to calculate the lowest common multiple.
Day 8 part 1:
part 1
Day 8 part 2:
part 2
3
u/horsecontainer Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python]
I had no idea about the lcm strat until seeing it on here, and then I just wrote it in a way that seems mostly good to me.
3
u/thinnerthinker Dec 08 '23
[LANGUAGE: OCaml]
https://github.com/thinnerthinker/aoc2023/blob/main/bin/day08.ml
Caved and went for LCM of all combinations of cycles after my dumb and less-dumb bruteforce both took more than 5 mins.
Based on other solutions, it looks like I only need to search until the first Z? Can't figure out if the math comes out like that, or it's just a fluke. Still tried all combinations of path-lengths to all Z-s just to be sure :)
3
u/juanplopes Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python]
Both parts in 8 lines, 0.1s runtime.
These are my least favorite days in AoC, where you have to analyze the input to come up with an algorithm. That's how bugs are made in real life: by assuming things about the input.
https://github.com/juanplopes/advent-of-code-2023/blob/main/day08.py
3
u/WaitForTheSkymall Dec 08 '23
[Language: Rust]
Code on Github
For part 1, I just brute forced it. Build the map, and follow instructions until you find ZZZ. Runs quickly so no need to optimize further. I cheated for part 2, please forgive me! I couldn't figure it out at all. Math ain't my strong suit.
Part 1 runs in 600µs
Part 2 runs in 3ms
3
u/GigaClon Dec 08 '23
[LANGUAGE: python]
I had fun with generators and python's itertools and had this weird line
len(list(takewhile(lambda x: x[-1] != "Z", iter)))+1where iter is a function that yields successive steps for the function.
When in part 2, i noticed that it didn't finish in 30 seconds, and having done 2019 day 12 recently, figured each was independent and used LCM and there we go.
https://replit.com/@gigaclon/Advent-of-Code-2023-Day-8-for-reddit#main.py
3
u/daic0r Dec 08 '23
[Language: Rust]
https://github.com/daic0r/advent_of_code_2023/blob/master/day_8/src/bin/part1.rs
https://github.com/daic0r/advent_of_code_2023/blob/master/day_8/src/bin/part2.rs
Part 1 uses brute-force, part 2 LCM
3
u/SkullKnight9000 Dec 08 '23
[LANGUAGE: SQL (PostgreSQL)]
Solution with LCM method
I tried an implementation without LCM. It was difficult to express, and after expressing it crashed the database 😂
3
u/jaccomoc Dec 08 '23 edited Dec 09 '23
[LANGUAGE: Jactl]
Jactl
Part 1:
Part 1 was pretty easy. Just read the nodes into a map of maps where the submaps are keyed on 'L' and 'R' so we can lookup the move directly. Saves having to convert L to 0 and R to 1 if we used lists/arrays instead. Then just iterate while the node is not ZZZ and return the count:
Part 2:
For part 2, it was soon clear that brute force tracking all paths at the same time was going to run for close to eternity so obviously we needed to work out the length of the individual cycles and find the least common multiple.
Luckily the step count until the first terminating node turned out to be the cycle count for each ghost (although in general this does not have to be the case). I took the lazy approach and the code assumes that this is the case.
Interestingly, it turned out that it was only necessary to find all of the unique prime factors as each cycle was only the product of two primes but I felt a bit dirty not properly implementing the least common multiple function even though it was not strictly necessary:
Code walkthrough
3
u/bulletmark Dec 08 '23
[Language: Python]
3
u/chubbc Dec 09 '23
[LANGUAGE: Uiua]
Yea... this one ended up pretty ugly. Might need to come back and see if I can restructure this better. Ah well, works for now. Pad link.
3
u/onrustigescheikundig Dec 09 '23 edited Dec 09 '23
[LANGUAGE: OCaml]
github
I'm beginning to think that my parser-combinators aren't very concise; my code is more than half parsing again. Anyway, this solution is basically the same as everyone else's: build a map of the nodes, set up a way to infinitely cycle the directions, and away you go. I had a massive performance bug in my graph traversal in the first version when it looked something like this:
Now, this code is suboptimal because
Seq.unconsreturnsSome (head, tail), but I'm throwingtailaway and calculating it again usingSeq.droplater on, which is needless duplication. The fragmentation was just part of the problem solving process. For reference, the proper code looks something like this:For whatever reason (I would guess related to continuing to use a
Seqin its original form after accessing one of the items withuncons), matching idiomatically onSeq.unconsled to a speed-up by three orders of magnitude, from ~6 s combined for Parts 1 and 2 (with Part 2 running with parallel execution!) down to the millisecond range (single-threaded). I don't know WTF the OCaml compiler is doing, but that seems disproportionate for the change. I'd love to hear from anyone who knows more.Also, I originally kept track of and returned the path from my traversal algorithm for debugging purposes instead of just returning a count; the latter is in theory more efficient. I tried changing it to only keep track of the count instead, but that led to identical runtimes. I guess the compiler did some more voodoo there.
3
u/bofstein Dec 09 '23
[LANGUAGE: Google Sheets]
First one was pretty quick, second I was worried would be a lot harder but was made easy by the fact that each A node only ever reaches one Z and cycles uniformly.
The core of it is just turning L and R into the column numbers to look up (after splitting up the input, and doing a VLOOKUP on the node above. Then run it for 30k rows and us another column to find what step it is that shows ZZZ (or ends in Z for part 2).
Part 2 I didn't think I could do at first; I could tell it should cycle at some point and then you could multiply those intervals to get the LCM as the answer, but I didn't think each would be paired to a single end node and immediately cycle, meaning that all it needed was taking the same thing for Part 1 and finding the LCM of those. First submission was wrong because I used an online calculator, not knowing Google Sheets had an LCM function, which had commas.
https://docs.google.com/spreadsheets/d/1epTmQdsIcKFICgCJQuY95H5dH5RH93UxmYtcD5XjjTg/edit#gid=1597842667
3
u/AnxiousMasterpiece23 Dec 09 '23
[Language: JavaScript]
Guessed on the relationship of paths for part 2. When iterative wasn't converging after several minutes I went looking for a math solution. I had no way of verifying that LCM was going to apply but it felt like a planetary alignment problem once the single cycle lengths of each path were known.
https://github.com/ccozad/advent-of-code/blob/master/day-8.js
3
u/Kintelligence Dec 09 '23
[Language: rust]
https://github.com/Kintelligence/advent-of-code-2023/blob/master/day-08/src/lib.rs
Really not a big fan of how many assumptions I've made about the input to speed this up. It's still the slowest day by far. Wish I could optimize it to less than 100µs. These cycle tasks are always hard, but a good exercise in trying to understand what edge cases don't appear in your input so you don't have to handle them.
Benchmarks Part 1 Part 2
3
u/doodlebug80085 Dec 09 '23
[LANGUAGE: Swift]
Today's question was fun! I'm grateful all we needed was LCM.
Code
3
u/fizbin Dec 09 '23
[LANGUAGE: Python]
Yet another python solution
I think that the only interesting thing about mine compared to all the other solutions here is that I validate that the short
lcmlogic will actually work on the input (throwingValueErrorif not) before computing the answer.