r/adventofcode • u/daggerdragon • Dec 12 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 12 Solutions -🎄-
--- Day 12: Passage Pathing ---
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:12:40, megathread unlocked!
56
Upvotes
25
u/CCC_037 Dec 12 '21
Rockstar:
Part 1:
Part 2:
Fairly naive solutions. Take quite a while to run. A... little unsure how to do it faster.
It works, though. Just needs a bit of waiting.
5
u/RojerGS Dec 12 '21 edited Dec 13 '21
Used the same recursive function to solve both parts, given that solving the second part is essentially building a path that revisits a small cave, and at that point the restrictions match those of the first part.
Vanilla Python 3 follows; all my solutions are available on GitHub.
4
u/[deleted] Dec 12 '21
Python3
Getting better at recursion! I had some issues with part two because I managed to glance over the whole "one time at start" thing, but I am proud to say Advent of Code is making me much better at recursive algorithms!
4
u/TheOx1 Dec 12 '21 edited Dec 13 '21
Haskell
Quite happy with the solution for today. I am using regex for parsing the input for the first time in Haskell and Maps for constructing the graph :)
Code
4
u/theSpider_x Dec 12 '21 edited Dec 13 '21
C
Wow I struggled a lot I thought I was not going to be able to make this. Code is horrible and runs slow but I was tired after a lot of frustration so I was just happy I got the correct results. Definitely worth revisiting to make it better.
https://github.com/fuzesmarcell/aoc/blob/main/2021/day_12.c?ts=4
6
u/jayfoad Dec 12 '21
Dyalog APL
3
u/jonay20002 Dec 12 '21
3
u/[deleted] Dec 12 '21
I was a bit miffed that it didn't say the infinite loops wouldn't be possible. I spent a good deal of time thinking about the infinite loop situation before realising the input was specially crafted to not include any adjacent "big" caves.
3
u/TiagoPaolini Dec 13 '21 edited Dec 13 '21
Python 3
The problem becomes easier once one notices that there are no big caves linked directly to each other, so it is not necessary to worry about an infinite loop between two big caves. Not that it took me a while to figure that and try a harder solution 🙃.
I also used this puzzle as an excuse to try some advanced class features on Python. I made each cave a singleton, that is, when I try to create a new instance of the same cave, it just returns the previously created instance. And more importantly, each cave stores which ones it is linked to.
I used recursion. Starting from the first cave: for each joint in a cave, I applied the pathfinding function. On each step I counted the current number of visits in a small cave. If it was bigger than the limit, the path was dropped. I also checked if the path reached the start or the end positions, and stopped the search if so. I stored the paths that successfully made to the end while meeting the visits limit.
On my old laptop Part 1 takes less than a second to compute, while Part 2 takes around 10 seconds. It took me the entire day to get to the solutions, but it was worth the learning! 😀
Code: https://gist.github.com/tbpaolini/74c3009400a24807eb96aa70a4615c07
4
u/Smylers Dec 12 '21 edited Dec 12 '21
Vim keystrokes, using an iterative, rather than recursive, algorithm. Load your input into Vim, type this (the two long lines at the beginning are copy-pasteable), and your part 1 answer will appear:
Do try it, and if you have any questions, just ask below.
I'll try to update later with an explanation, but right now I need to go and wash the hair of a child who's just returned from Cub camp.Update: The algorithm starts with a counter set to
0on the top line, followed by a single line containingstart, and then on each iteration it replaces each line with all the alternatives that continue from there, then deletes any which have reachedend, updating the counter for each, and also deletes any which contain duplicate small caves.Ignore the first 3 lines for now, and look inside the
@bloop definition. First it adds a comma to each line (well, line 2 onwards, to leave the counter alone), then runs@awhich (vague handwavey gesture) makes copies of each line for each cave which can be reached from there. So the first example from the puzzle description becomes:The following
:g//command deletes any lines which end with a comma — that is, those from the previous iteration. We couldn't just append the next possibility on to an existing line, because there's a varying number of connections from each cave; so each valid connection appends to a duplicate line, and the trailing commas handily serve a dual purpose of separating the cave labels in each path and indicating which lines are no longer needed once all the next moves have been found.Then check if we've reached the end: any line matching
/,end$/represents a successful path, which can be counted:The
:silent!is so that an iteration without any such matching lines doesn't cause an error and end the loop. Thed(which, following:g//is the:dEx-style command, not thednormal-mode keystroke) deletes the line — once we've completed a path, we don't need it any more — and{⟨Ctrl+A⟩in normal mode increases the counter on the first line.On the remaining paths, prune any which are invalid:
Specifically, if any lower-case label (
/\v<\l+>/) is repeated on a line, then that isn't a valid path, so get rid of it.(Part 2 should be possible using this same basic algorithm: it would just involve using different pruning criteria at this point. But given how big the numbers get, I'm not sure I want to try it.)
Then repeat with
@b. Just before that, go to the top with{and then down a line withj. Not because we need to be on that line, but because once all the paths have been found, thejwill fail — and we need to have something fail at that point, to end the loop.So what about that handwaving and setting up
@ato make copies of each path with the options for the next cave? That's what the first few lines do — transforming the input into Vim commands that make those changes. Each tunnel is bidirectional, so duplicate and reverse each input line, then delete those which end with-start, since we're never going back there:At this point the first example input looks like this:
Now transform each of those into a
:s///command which will do the right thing on lines containing paths so far:Or, rather, since that transformation is itself a
:s///command, turn each one into a:s!!!, which is exactly the same thing but with different delimiters, so the slashes don't get in each other's way. The sample input has now turned into:If you peer closely, you can just see the original ‘from’ and ‘to’ cave labels among all that punctuation. Just looking at the first in more detail, it says: “replace any line which contains anything at all followed by
startas an entire label followed by a comma and the end of the line, with that entire line, a line-break, a copy of the entire line, and the labelA”.Then join all these to a single line with
V{J(which works because the previous substitution matched every line, so must leave the cursor on the final line), and do0r:to replace the initial bar with a colon.|is the Vim syntax for separating multiple Ex-style commands on a single:line. That's why the substitution put a|at the start of each line; it ends up between the commands when joined together.Delete that into register
a, set up the counter and start label, and we're ready to iterate, with@acontaining the Vimified version of the input connections.If you want to try this on multiple input files, you need to set up
@aagain for each one (though you can avoid retyping much of it with:and the ⟨Up⟩ key to repeat from the command history), but@bdoesn't change: having got to0\nstart, you can just type@band watch what happens. On my real input it takes about 5 seconds.To step through it, just omit the looping
@binside@b's definition, then type@bto watch each iteration.2
u/DFreiberg Dec 12 '21 edited Dec 12 '21
Mathematica, 1881 / 852
I lost a significant amount of time today in over-engineering the solution; I figured that there would be far too many paths to brute-force enumerate them all (either for part 1 or part 2), and so I spent most of my time implementing Dijkstra's algorithm to tally up all paths without enumeration. It was able to calculate the answer to the most common misreading of part 2 (visiting any small node twice, rather than visiting just one twice) in a few seconds, covering over 120 million paths. And then it turned out that brute force worked just fine and I could have saved myself the trouble.
[POEM]: All Roads Lead to Home
Today's poem was much too large to fit in this comment section, so instead, click here to read it.
2
u/autid Dec 12 '21 edited Dec 12 '21
FORTRAN
The jank is real today.
edit: too long to paste
https://pastebin.com/KN6hejgz
2
u/Outrageous72 Dec 12 '21 edited Dec 13 '21
C#
CaveRoute does the heavylifting. Determines if it is allowed to add a cave to the route. For speed I only kept a hashset of caves and not a List, the true route is not needed, only the last visited cave to know where to go to next. The start and end cave have their connections directed, so we do not need to check for revisits of start, it is just not possible.
paste link
2
u/yschaeff Dec 12 '21 edited Dec 16 '21
Python.
Just to be silly, solution A is in the real part of the complex answer and B in the imaginary.
2
u/Fyvaproldje Dec 13 '21 edited Dec 13 '21
Typescript
https://github.com/DarthGandalf/advent-of-code/blob/master/2021/solutions/day12.ts
2
u/Spirited-Airline4702 Dec 13 '21 edited Dec 15 '21
Python Solution:
Implemented using recursive DFS and having a separate node_allowed() condition for each part.
Part 1 + Part 2
46
u/4HbQ Dec 12 '21 edited Dec 12 '21
Python, single function for both parts, because (after visiting a small cave twice) part 2 is identical to part 1:
13
u/jonathan_paulson Dec 12 '21 edited Dec 12 '21
20/4. Python. Video of me solving.
I'm pleased with my times considering I submitted a wrong answer to part 1!
Nice to see a graph problem! Is there a faster algorithm than tracing out all the paths?
10
u/mcpower_ Dec 12 '21
Python, 11/2. Nice small adjustment for part 2.
Input:
Part 1:
Part 2:
(the
curvariable had type annotations because I needed IDE autocomplete for str.islower() :P)10
u/relativistic-turtle Dec 12 '21
IntCode
Misread puzzle text for part 2 first. Thought every individual small cave could be visited twice. Luckily the examples help me diagnose that (relatively) quickly.
However I spent an awful amount of effort debugging an annoying compiler bug: comparison against negative numbers triggers memory errors (like
buffer[i] == -1, or even5 == -1. Kaboom!). Probably should fix that...8
u/miran1 Dec 12 '21 edited Dec 12 '21
Python
Recursive DFS, once again. Solution for both parts:
Repo: https://github.com/narimiran/AdventOfCode2021
8
u/axr123 Dec 12 '21 edited Dec 12 '21
Python with memoization ~20 ms
I haven't seen many solutions yet that use DFS with caching, but it turns out that gives almost a 10x speedup.
Update: Using suggestions from u/azzal07 I updated the solution. Now it's a bit more readable and as fast as it gets for plain Python:
Running the Python interpreter with an empty file gives about the same runtime.
7
u/__Abigail__ Dec 12 '21
Perl
First we read in the data, keeping the map of the cave as a graph, and using a 2-level hash to keep track of connections. All connections go both ways, except for the start and end caves:
Now we do a breadth-first search of the cave system. We'll use a three-element array to keep state of where we are:
We initialize this with just one state: when we are in the start cave:
We haven't visited any cave yet, so the set of visited caves is empty, and we certainly have not visited a small cave twice.
We need two variables to keep track of the number of paths (one for each part):
We now process the
@todoarray with states:First, we check whether we are at the end cave. If so, we increment the counts, and continue with the next state. We only count a path for part one if we did not visit a small cave more than once.
Now, we terminate this possible path if we are in a small cave, have visited this cave before, and we've already visited a small cave twice:
Now we add each of the neighbouring caves to the
@todolist, and we're done with the loop:All what needs to be done is print the results:
Full program on GitHub.
7
u/BadNeither3892 Dec 12 '21
Python, Part 1 solution. Pretty satisfied with it, at least in terms of conciseness.
6
u/AllanTaylor314 Dec 12 '21
Python3 (218/98)
BFS to find every path. Probably not the fastest way to check for duplicate small caves, but part 2 runs in a few seconds. First time ever on the leaderboard!
6
u/azzal07 Dec 12 '21
Postscript, PS.
Bit slow today, but not too bad. Just a straight forward dfs on both solutions.
Awk, when the problem gives you
lemonslimes5
u/tymscar Dec 12 '21
Today was more difficult than the previours days, for sure, but I also spent like 20 minutes trying to figure out why my part 2 was not working. It was because I thought any lowercase place can be visited twice, not only one of them.
Part1 and part2 in Javascript
5
u/jmpmpp Dec 12 '21
Python 3, recursive depth-first. (wow, recursion is magic!) without any packages. I set up a dictionary mapping each room to the set of its neighbors. Here's the code after that:
5
u/semicolonator Dec 12 '21 edited Dec 12 '21
Python, 29 lines
Non-recursive solution. Create a queue of all open paths. Add the first path to the queue which is a path with a single node,
start. While there are open paths in the queue, pop a path, check if it ends inend(if it does increase a counter), and then add k new paths to the queue, one for each neighbor of the last node in the popped path, if one of the following conditions holds: 1) neighbor is uppercase or 2) neighbor is not already in path or (in case of part2) 3) neighbor is contained in the path only once.5
u/Crazytieguy Dec 12 '21 edited Dec 12 '21
Rust
https://github.com/Crazytieguy/advent-2021/blob/master/src/bin/day12/main.rs
At first I used a HashSet to keep track of which caves were visited, and it worked fine. As a fun challenge I wanted to avoid cloning on each recursion, so now each cave has an index and I keep which ones were visited in an array of bool. This resulted in x10 speedup :)
5
u/Derp_Derps Dec 12 '21
Python
Vanilla Python, compacted.
First, I generate a dictionary, that contains a set of all adjacent caves for every cave. But I make sure, that the you can only exit the "start" cave.
With this setup, I use a recursive function to find all ways. In this function, I loop through all neighboring caves (
c). I also determine, if the neighbor is a "lowercase" caveandis already in the pathv. If this is the case, this cave will only be visited if the "a small caves was visited twice" counter is still 0 (b). Then, I call the same function again recursively with the growing path.This way, part 1 is basically part 2 with the "a small caves was visited twice" counter already at
1.5
u/AtomicShoelace Dec 13 '21
Python using
networkx:5
u/[deleted] Dec 13 '21 edited Dec 13 '21
Python Part 1
Python Part 2
5
u/Chrinkus Dec 13 '21
My C Solution
Whew! I've tapped out in previous years on graphing problems. This year I grabbed my Cormen book and got to reading. Did a lot of sketching through the day but finally got a chance to type it up.
I know that for many, the weekends DO give extra time for solving these problems. That is, they do if you don't have young children! I could not sit down at my desk all day until they were off to bed.
Gonna relax for an hour to see the next problem drop then get to bed myself.
5
u/Rtchaik Dec 13 '21
Python
It's short. I hope it's a good solution :)
5
u/joshbduncan Dec 15 '21
Python 3: This type of puzzle always takes me the longest 🤬... Still playing catch-up from the weekend...
4
u/r_so9 Dec 12 '21 edited Dec 14 '21
F
4
u/mebeim Dec 12 '21 edited Dec 12 '21
1494/1874 - Python 3 solution - Walkthrough
What can I say... the problem was pretty simple, I'm just slow at thinking algorithms on graphs :'). My solution is DFS with a "visited" set for every single path instead of a global one, plus the additional rules dictated by the problem to include/exclude neighbor nodes. In this case DFS is better than BFS for the second part since the number of different paths "explodes" pretty quickly.
A fun thing to notice is that due to the nature of the puzzle there cannot be any edge connecting two uppercase nodes together, otherwise the input graph would contain cycles and there would be infinite paths from start to finish.
4
u/voidhawk42 Dec 12 '21
APL, pretty basic DFS for both parts:
4
u/zndflxtyh Dec 12 '21
Python
4
u/ephemient Dec 12 '21 edited Apr 24 '24
This space intentionally left blank.
4
u/michalopler Dec 12 '21
Python, both parts can fit into a single tweet (<280 chars)
4
u/RikvanToor Dec 12 '21 edited Dec 12 '21
Rust. I made it terribly ugly and unreadable while attempting to speed it up. That worked I think, part 2 runs in 0.015s on my laptop. The main trick was converting all caves from strings to power of 2 integers. That way, instead of storing a list of visited caves, you can use a single integer and do bitwise comparisons to check if you've visited a cave before.
Update: I've got part 2 down to 0.4ms now
4
u/mockle2 Dec 12 '21 edited Dec 12 '21
python, both parts, just a straightforward recursive depth first search:
4
u/Steinrikur Dec 12 '21 edited Dec 12 '21
bash
No idea what my algorithm is called. I just brute force my way through all the paths. 2 seconds for part 1, about 44 seconds for part 2.
The logic to check if I should continue was hacked to use the same function for part 2 - it could surely be improved.
Edit: Simplify logic for when to go deeper. One if statement instead of three.
4
u/narrow_assignment Dec 12 '21
AWK
Part 1:
4
u/RandomGrumpy Dec 12 '21
Typescript
Part 1
Part 2
4
u/[deleted] Dec 12 '21
Python, proud of part one because it's the first time using recursion outside of uni and it worked first try. Part 2 for some reason I couldn't get it to work :(, It worked for all 3 test cases but it just seemed to run out of memory or something in part 2.
Solution
4
u/__Abigail__ Dec 12 '21
Blog post Passage Pathing (Perl)
4
u/cggoebel Dec 12 '21 edited Dec 12 '21
Raku
4
u/TheSolty Dec 12 '21 edited Dec 12 '21
Python (no libs)
A little recursion never hurt anyone, did it?
EDIT: Check reply for a shorter version, which does what the better solns do :)
4
u/RudeGuy2000 Dec 12 '21
scheme (racket)
today I was able get part 1 working instantly without any bugs. but that didn't happen for part 2. sigh...
4
u/MikeMakesMaps Dec 12 '21
Rust. So I learned today that graph structures are hard in rust. It took about an hour to just parse the input into a usable form, Part 1 was fine, but I really struggled with part 2 (made worse by limited time) and in the end had to get a hint, but it was easy enough to implement once I knew.
Github link
4
u/WayOfTheGeophysicist Dec 12 '21
Python 3. Figured I'd learn some more
networkx. Was useful for the "smol" attribute in the end and easily getting the neighbors. Full code is on Github.Figured out that part 2 is basically part 1 with one extra step. Bit finicky to actually make it work, but in the end, another keyword argument just did the trick.
4
u/No-Rip-3798 Dec 12 '21 edited Dec 12 '21
Go
I woke up to a friend boasting that he had found a solution in C++ that could solve part 2 in
~150µsusing some clever dynamic programming technique. That's why I took the time to write this bad boy in Go using a somewhat classic recursive algorithm, but with the right data structures to allow for efficient memoïzation, and stopped when I finally got these benchmark results:Edit: Thanks to a very cool tip on the Discord Gophers server, I could even knock it down by reducing the number of allocations needed for the memoization.
4
u/Gravitar64 Dec 12 '21 edited Dec 13 '21
Python 3, Part 1&2, 359 ms
4
u/prendradjaja Dec 12 '21 edited Dec 12 '21
I found a pleasant little shortcut for implementing the "a single small cave can be visited at most twice" constraint. (I wonder if this was an intended solution? I probably am not the first person to spot this, though :) )
It's a little too "clever" to use in real life, and would probably have to be replaced with a more obvious solution if the revisit constraint was changed, but I thought it was nice!
Python 3
https://github.com/prendradjaja/advent-of-code-2021/blob/main/12--passage-pathing/b.py
4
u/aexl Dec 13 '21
Julia
I used a recursive graph traversal function to solve the problem. The first version worked fine, but was kinda slow (0.5s) because I was storing and copying all the paths. Then I've realized that I only need to keep track of the nodes starting with a lowercase character. This can be stored in a set and copying this set is not necessary because the elements can be removed at the right moment. This improved the runtime a lot (down to 70 ms). The last improvement was to store the nodes as integers (negative integers for lowercase nodes, positive integers for uppercase nodes).
Github: https://github.com/goggle/AdventOfCode2021.jl/blob/master/src/day12.jl
4
u/Zach_Attakk Dec 13 '21
Python
The data structure I decided to go with is a list of strings to represent the path. So my result set is
List[List[str]]After this, my solution hinges on a little function that yields every possible connection from the last node in the path.
For Part 2, the lowercase check had to change from
n not in ito a validation function that looks like this:It sucks and it's slow, but it works.
Count the nodes. If it's lowercase and there's more than one of it, we've used our repeat so if this new node already exists int the list it fails validation.
To find 74200+ paths takes 5.2 seconds, most of which is spent in the validation function, so it can definitely be optimised.
Part 1, Part 2
4
u/tuisto_mannus Dec 13 '21 edited Dec 23 '21
Golang
This is my favorite puzzle so far. I made two solutions. In one solution I'm using Breadth-first search (BFS), in the other one I'm using Depth-first search (DFS) with caching.
Solution 1 runs in 95 ms
https://github.com/c-kk/aoc/blob/master/2021-go/day12-bfs/solve.go
Solution 2 runs in 0.3ms
https://github.com/c-kk/aoc/blob/master/2021-go/day12-dfs/solve.go
Instructions on how to run the solutions in Go
https://github.com/c-kk/aoc/blob/master/2021-go/instructions.md
Learnings
4
u/rawlexander Dec 15 '21
That was the hardest so far for me. Pretty hacky and takes ~8s to finish.
R / Rstats: Code
I also stream the process. And make videos for the results. :)
1
u/mynt Dec 12 '21 edited Dec 12 '21
Python 3
Was quite happy with this, the boolean at the start of the list is whether or not a small cave has been revisted. Below solves part 2 Set track to [True, 'start'] to solve part 1.
#!/usr/bin/python3
1
u/jkpr23 Dec 12 '21 edited Dec 12 '21
Kotlin
Today we used
Map.withDefault { ... }to help get to something like Python's defaultdict.The solution is a fairly straightforward DFS recursion.
1
u/TheZanke Dec 12 '21 edited Dec 12 '21
Javascript
I started working on a reduce-based solution but pivoted when I wanted to be able to print all of my paths to compare against expected output. Runs in ~100ms with Jest.
Github
1
u/aimor_ Dec 12 '21 edited Dec 13 '21
MATLAB
Not a good solution today (better solution below), just brute forced it. What's the efficient way to solve this? Maybe just take the transition matrix and matrix multiply, with diverging matrices whenever a small cave is reached? Might try that out.
https://topaz.github.io/paste/#XQAAAQAUBQAAAAAAAAASiASoOj4/ciRIj+NxYWCy6lQg6K+kzBrwtSJpG/hL/POqhSByPPr3FK9UaX+Vh2+vKLzPIy88LE8JSdjteccUYKw2PM7uIlnFQGAPCUTwOPjNCXbFBpRCY0G1jQcloB58Npmlrz5BgJSoZt5cfjuIkmz+8a4h1oGQAUgmRK1pwDwJ2SphOoeQvwxfFrtmPbmWPUe/zzaD8qR5R33wNUvzBVch09iHXcg0RLcAwfxeSMbuxwz6Jch6deVmXXKYyphCY3yTlj1rEfh0TOj6qRaIeQoV1vv1XYM3JFAAGY9iRKx5uFBTn11Q6Z646ZYAH5kpI4v/PKR4z9HXyhh8ikeNTRTFLMZhi+aXmJ4Es3n/9luBnMxfMext5Y+O7g0khlEKqJdC3aHXqL0Ggo7Mx8HlrPDWtHiAsAtfDhxuT/Rj/XFxXiuM49cLBg1cUl2iFlqnSI4IFrY9SMkF2TdoBkEkt5FiLBTn5u/nYfrtROfEPTJbOcY5E5iWb2o3q1ubXvvVjWN2g7qHSrURpUrwhb4WdRW1IY7lHGTsvUi+eGtVUvhN8I2Z+72dxgbhJtXBzW25nsJJUBDx7XaKR5Ua8CFjLO2Mb9cVcaAipNljObQux2tei4rXAf/bJKj4D8qax8izkAkrEMZwbxQP0ytaRErnCs2dytfIIMQRwBkniZHVlhm0sKi5KGFi3f7EQVjSg0SC8gCmgSjQb1aV69KrF+a2YjZq5mStRNtXNDKmnFP/0fWptw==
1
u/[deleted] Dec 12 '21 edited Dec 16 '21
Perl
Part 1
Part 2
1
u/ishdx Dec 12 '21
here's an inefficent one https://gist.github.com/skejeton/0354618e994b0e1fc2017f8dc360ce13
1
u/Fozruk Dec 12 '21
Scala:
https://raw.githubusercontent.com/findus/aoc21/master/src/main/scala/day12.scala
1
u/ankitsumitg Dec 12 '21 edited Dec 13 '21
Reusable method for both part 1 and 2: GIT Link
1
u/YourVibe Dec 12 '21 edited Dec 13 '21
Typescript, Angular code
32 ms first part, 1.5s second part.
Edit: https://raczeq.github.io/AdventOfCode2021/#/2021/12
I will later add a link to a web page with the visualization after I finish it :DFor now, you can see the rest of the visualizations here:https://raczeq.github.io/AdventOfCode2021/#/1
u/Timmeh7 Dec 12 '21 edited Dec 13 '21
C++
1
u/YayL_official Dec 12 '21 edited Dec 13 '21
C++, recursively looping through every branch of a node. I think it is a DFS algorithm but I am not sure. Please correct me if I am wrong.
More of my code can be found here or on my github: https://github.com/YayLOfficial/AOC/blob/master/2021/Day12/Part2/main.cpp
Thanks to AOC I have learned so much, thank you! :)
1
u/pb554 Dec 12 '21 edited Dec 14 '21
Python
1
u/ficklefawn Dec 12 '21
Golang
AoC is getting a bit tedious for me, where I come up with a solution quickly but debugging my implementation takes a while - so I guess I'm training to write tidier code. I leave out the trivial functions like
mapCaves()that reads the inputs, andcurr(),copy()etc. Interesting parts below.1
u/DSrcl Dec 12 '21
Second part in python.
1
u/toastedstapler Dec 12 '21 edited Dec 13 '21
zig
rewrote my braindead 6am code and got my runtime down from 85ms to about 4ms. not sure how much more thought i want to put into today, especially when i still need to redo day 5 but fast
https://github.com/jchevertonwynne/advent-of-code-2021/blob/c070fe3b98434e387ccbc331163088ef895dcadb/src/days/day12.zig
1
u/hamzaabamboo Dec 12 '21 edited Dec 13 '21
I want to share my solution a bit since I think it's kinda have my unique touch to it XD.
tl;dr I used lots of sets, and sets helped me eliminate duplicate paths :P
For the first part, the algorithm is to "go to every path until you run out of places you can go". the signature for findPath was `findPath(startNode, availableNodes)` which availableNodes is a set that contains all the nodes that is still available for visit. As you can Imagine, after a node gets visited it gets removed from the set. After that you rinse and repeat until you land at 'end' node. (I think there are better explanations for this kind of algorithm around here)
However, for the second question, instead of keep track of a set of available destinations to visit. I decided to first populate a list of amount of visits to each destination (start/end gets one, small cave gets 1 or 2, and large cave gets infinity). Then to match with constrain of the question. I make a list of list of visits (So each list, one selected small cave would get 2 visits and other will get 1 visits) and slightly modify findPath to "go to every path until you run out of visits"
But wait, if you run that much time wouldn't you get lots of duplicate paths ? you might ask. Yes I just keep the paths in tuples and let python handle finding unique paths XD
I think the code is simple enough for my brain to follow and solve.
The code is here (Python 3)
1
u/EnvironmentalNeck705 Dec 12 '21
Advent of Code always teaches me something new! Today was especially fun because I learned how to implement graphs in a simple recursive solution. Below I have linked my solution.
https://hastebin.com/inudulonax.java
1
u/fmardini Dec 12 '21
OCaml
1
u/JacobvanP Dec 15 '21
Simple, not the fastest, solution in C#.
1
u/j4nd8r Dec 19 '21 edited Dec 19 '21
Scala
Quite a challenge to get a correct, log4shell vulnerability also prevented me from focussing.
anyway, my recursive scala solution.
2. my findEnd function returning a list with all possible roads, The smallCavesVisited parameter was introduced for step2.. findEnd has 4 recursive calls, one of which is an argument of another recursive call.
Full solution here
3
u/leijurv Dec 12 '21 edited Dec 12 '21
Python, 43rd place, 14th place
Screen recording https://youtu.be/_ikWKGfjIWw
Part 1
Part 2
3
u/[deleted] Dec 12 '21
Python (networkx)
https://colab.research.google.com/drive/1zyN53RTuuqJvcVkLQYpHPhggwm6PdVTn?usp=sharing
Just recursively checking all paths
3
u/SuperSmurfen Dec 12 '21 edited Dec 12 '21
Rust (1492/567)
Link to full solution
Not seen this variation on the number of paths problem before. Fun problem and really happy with my part 2 placing!
I used more or less the standard recursive backtracking algorithm. Initally I used a hashset of seen nodes, however keeping tracking of the path makes part two a lot simpler:
You can reuse the implementation for part 1 by saying you have already visited a node twice at the beginnning. So the same function can be used for both parts:
I'm sure there are optimizations you can do here but finishes in about
48 mson my machine.3
u/death Dec 12 '21
Day 12 solution in Common Lisp.
3
u/xelf Dec 12 '21 edited Dec 12 '21
Python
fairy straightforward bfs today, fun times, hope there's more
relatively short I suppose:
3
u/kbielefe Dec 12 '21
Scala 3
DFS with tweaks for tracking visited caves. There is probably a way to count without actually traversing every path, but this runs fast enough that I can't be bothered. I was worried that part 2 would have an answer in the trillions. Goes to show it doesn't always pay to pre-optimize. I'm interested to see if anyone solved it that way, though.
3
u/nlowe_ Dec 12 '21
Go, 3030/3121
Fairly straightforward but had to do lots of debugging today.
3
u/daniel-sd Dec 12 '21 edited Dec 12 '21
Python
First Draft:
5471 and 4179 but I started 30 mins late, oops. Took about 20 minutes and 26 minutes respectively.
BFS with a stack. Added a unique element to the front of the path to indicate one duplicate was used in part 2.
Part 1 - 35
Part 2 - 35
Cleaned up:
Changed from storing paths as strings to lists and then removed the visited set since I forgot BFS paths are unique by nature :P
Part 1 - 22 lines
Part 2 - 24 lines
3
u/Smylers Dec 12 '21
Perl. With
$connectioncontaining the connection map read from the input, the counting function for part 2 is just:Because the
%seencount is passed by value (as a list of pairs) rather than by reference, there's no need to localize anything: additions to it can't affect previous levels of recursion when returning to them.The full code includes an alternative implementation which avoids the iteration through
values %seen, by having a flag to indicate once any small cave has been seen twice. But it's only about 10% faster, so I don't think it's worth the additional complexity.3
u/The_Fail Dec 12 '21
Julia
Runs in 1.75ms (both parts + I/O) on my laptop. The key insight to optimize is to eliminate the big caves at the cost of additional connections. That effectively give you a smaller graphs with edges carrying a factor. This cost the traversal down A LOT.
3
u/clouddjr Dec 12 '21 edited Dec 12 '21
Kotlin
All solutions
3
u/mariushm Dec 12 '21
PHP
Seems I'm the first with a PHP solution, guess I woke up early enough today.
Finally made a recursive function this month : https://github.com/mariush-github/adventofcode2021/blob/main/12.php
I'm eager to see if the guy that hoped to do all projects on Arduino succeeds with this day's problem, will definitely check his code if he posts it.
3
u/Diderikdm Dec 12 '21
Python:
3
u/bacontime Dec 12 '21
Python 3
I managed to get sub-1000 ranking for both parts (919/769). Obviously not as impressive as actually showing up on the leaderboard, But I'm chuffed nonetheless.
Here's where the data is loaded up:
Here's the solution for part 1:
Here's Part 2.
I gave each incomplete path a little flag to indicate whether the duplicate small cave had already been 'used up' for that path.
My solution for part 2 originally took over a minute to run. Instead of using
paths.pop(), I was looking atpaths[0]and then usingpaths=paths[1:]. That's O(1) vs O(n) complexity. 🤦 The corrected code above solves both parts in less than a second. Ah well. Sometimes making stupid mistakes is the best way to learn things.3
u/Durdys Dec 12 '21
F# https://github.com/DurdSoft/AdventOfCode2021/blob/main/AdventOfCode2021/Day12.fs
Perhaps slightly over engineered, but it’s always nice to be able to build up the solution from well defined types and functions.
3
u/encse Dec 12 '21
C# commented
https://github.com/encse/adventofcode/blob/master/2021/Day12/Solution.cs
3
u/lgeorget Dec 12 '21
C++ : https://github.com/lgeorget/adventofcode2021/tree/main/12
A depth-first visit implemented without recursion. First time this year I have a solution with execution time > 1s (1.3s approximately). There's room for optimization but it's not trivial (to me).
3
u/SpaceHonk Dec 12 '21
Swift
https://github.com/gereons/AoC2021/blob/main/Sources/AdventOfCode/puzzle12.swift
Textbook DFS, more or less
3
u/autra1 Dec 12 '21
PostgreSQL
Code
Nearly standard graph traversal with postgresql. Part2 is quite slow (~3sec), I'm pretty sure it's possible to do better.
3
u/iamnguele Dec 12 '21
Java
3
u/nervario Dec 12 '21
JavaScript, I made a recursive function getPath that receives cave and from that cave generate the list with all posibles path, I don't know if the code is optimal but it works in miliseconds.
3
u/Ok_System_5724 Dec 12 '21
C#
Again I didn't read the whole question before I got to an answer. One single small cave.
3
u/[deleted] Dec 12 '21
Python
I stayed up last night, but I couldn't wrap my head around part two with the lack of sleep. Got part 1 after trying too much. This morning I got part 2 after dreaming about the solution the whole night!
https://github.com/rbusquet/advent-of-code/blob/main/2021/12/day12.py
3
u/sdolotom Dec 12 '21 edited Dec 12 '21
Haskell
A very straightforward DFS solution with a
Settracing visited small caves. There's an extra flag that defines if we're allowed to visit the same small cave twice, and after the first such encounter it resets toFalse. For the first part, it'sFalsefrom the start, so both parts differ in a single argument. First part runs in 3ms, second in ~60ms.Full code
3
u/[deleted] Dec 12 '21
Swift
https://github.com/calebwilson706/AOC2021/blob/master/2021SwiftSolutions/2021SwiftSolutions/Day12.swift
3
u/thulyadalas Dec 12 '21
RUST
My solution works with a recursive search algorithm, Initially, I used a (&str, &str) tuple for edges of the graph. That version was doing the job around 50ms both parts.
Afterwards, using the same algorithm, I updated the edges to HashMap<&str, Vec<&str>> with a little bit redundancy by having both sides. That version was around 35ms.
In the end, I implemented a Node struct which uses integer hashes and it is below 20ms now.
3
u/quodponb Dec 12 '21
Python3
I'm finally beginning to struggle with these problems! I can't express my solutions as concisely and readably anymore as I felt like the other assignments allowed me to do. I'm looking forward to reading solutions from other people, and hopefully learning something.
3
u/timvisee Dec 12 '21 edited Dec 12 '21
Rust Reversed. Indices. Simplify input, remove large caves. DFS.
Part 1 0.015ms (15μs)
Part 2 0.272ms (272μs)
day01 to day12 total: 1.16ms
3
u/_Heziode Dec 12 '21
Ada
This is an Ada 2012 solution:
3
u/SwampThingTom Dec 12 '21
Python
While working on Part 1, I thought the second part would be about finding an optimal path. I was very happy to see it was just a simple change to the traversal criteria. Added a couple of parameters to my recursive graph traversal function and one more `if` test, making part 2 easy-peasy.
3
u/LinAGKar Dec 12 '21
Mine in Rust: https://github.com/LinAGKar/advent-of-code-2021-rust/blob/main/day12a/src/main.rs, https://github.com/LinAGKar/advent-of-code-2021-rust/blob/main/day12b/src/main.rs
3
u/pablospc Dec 12 '21 edited Dec 13 '21
Python
Used a dfs, keeping track of the small caves. For the second part I just looped through all the small caves, allowing them to be visited twice, and adding up the number of paths.
Currently the second part gets repeated paths, and I don't know if there is a way to fix that
3
u/cylab Dec 12 '21 edited Dec 12 '21
Kotlin: https://github.com/cylab/advent-of-code-2021/blob/main/src/test/kotlin/day12
3
u/goeyj Dec 12 '21 edited Feb 27 '26
[JavaScript]
Today was a bit challenging since I decided to try BFS to solve initially. It should have been a big red flag when part 1 took nearly 3 seconds to run. Got to a more or less proper DFS solution. Part 2 is running in about 300ms in Node for me.
3
u/Mclarenf1905 Dec 12 '21
Clojure
src
fairly happy with how this came out, always like opportunities to use
trampoline3
u/4D51 Dec 12 '21 edited Dec 12 '21
Racket
This is another case where using functions as arguments made it easier to refactor for part 2. Writing the valid-dest-2? function still took some effort.
In my first attempt, enumerate-all-paths used map instead of append. This produced all the paths, but jumbled up in various levels of nesting instead of just one list. I got the star for part 1 by flattening that and counting the number of times "end" appeared in it.
Also, even though part 2 generated 32 times as many paths as part 1, the shortest path was the same in both parts.
Github
3
u/RealFenlair Dec 12 '21
Clojure
Would love some feedback, I'm very new to the language. I first solved it in Python. The same implementation worked fine in Clojure (valid and walk), but creating the out-edges map was soo complicated - there has to be a better way, right?
3
u/ecco256 Dec 12 '21 edited Dec 12 '21
Haskell
3
u/wzkx Dec 12 '21 edited Dec 12 '21
J (lang) Not too easy...
3
u/zniperr Dec 12 '21 edited Dec 12 '21
C++
3
u/Killavus Dec 12 '21
Rust, I represented the graph using adjacency list:
https://github.com/Killavus/aoc2021/blob/master/day12/src/main.rs
3
u/sh_mango Dec 12 '21
Python
3
u/Atila_d_hun Dec 12 '21
C++
GitHub Solution
Not particularly great but I started off with a terrible brute force for part 2 so it's already much better!
3
u/MCSpiderFe Dec 12 '21
CSpydr
(CSpydr is my own programming language written in C)
All my AoC 2021 solutions in CSpydr: here
Part 1:
Part 2:
The same as part 1, except the
cave::pathsfunction:, which gets now called like this:
3
u/snhmib Dec 12 '21
Haskell,
full code
Only did part 1 since part 2 seems a bit pointless, I don't want to change the code from using a set to an array.
Anyway, I feel my parsing and graph-constructing code could use some work... It's almost 2x longer than my solution code!
3
u/cammer733 Dec 12 '21
Python, first solution that I've posted. Implemented with depth first traversals of a networkx graph. Started by overcomplicating it, but I'm pretty happy with my final solution.
3
u/thibpat Dec 12 '21
JavaScript (+ video walkthrough)
I've recorded my solution explanation on https://youtu.be/ZAVcCwO6Bcs
The code is available on github: https://github.com/tpatel/advent-of-code-2021/blob/main/day12.js
3
u/SomeCynicalBastard Dec 12 '21
Python
source
Initially I used BFS. I was pretty pleased with the result, but it took ~1.6s. Rewrote it to DFS. That saves a lot on searching back for visited small caves I guess. Running time is now ~0.4s.
The graph itself is just a Dictionary containing a list of neighbours for each cave. Searching is a recursive call. Most time is now spent in recursion, and some in calls to
isupper. Maybe some smarter encoding of the caves could cut that back, but I haven't thought of anything yet.3
u/stonebr00k Dec 12 '21
T-SQL
3
u/ramendik Dec 12 '21 edited Dec 12 '21
Python3, no libs. In line with my "no force like brute force" motto for AoC, what I have is a dict of sets that has every connected node for every node - which means every connection goes into it *twice* (as a->b and as b->a). Otherwise, just plain and simple recursion.
Also builds a string with the path; printing the string is currently commented out.
https://github.com/mramendi/advent-of-code-2021/blob/main/12.py
EDIT. I now see that this same kind of solution, in the same language with different syntactic sugar, was posted by u/SomeCynicalBastard . Kinda makes sense, it's an obvious Python approach.
3
u/HAEC_EST_SPARTA Dec 12 '21
Erlang
Solution on GitHub
I was initially hoping that I could finally play around with the
digraphmodule to solve this problem; however, it seems a bit too limited to represent the constraints of this problem. I ended up just using a map#{start => [end vertices]}to represent the graph, and added two entries for each edge to simulate an undirected graph. Maybe not the absolute best solution, but reasonably performant and easy to implement in Erlang.3
u/GrazianoS86 Dec 12 '21
Solution in Javascript, this one was so painful, I did use google quite a lot and try for so many hours and at the end the solution became incredibly simple
3
u/P3DS Dec 12 '21
Python
Part 1, Part 2
Anyway, simple graph object, and then traversed it with a recursive function. What it did was keep track of what has been walked, and then rejects small caves if they have been visited already. Used .islower to determine if it was a small cave or not. Assuming start and end were small for the first part was useful.
For part 2, also kept track of if you can still do double on a small cave, and also had to test whether it was the start/end or not (Luckily I had a boolean on the node for it. Thanks earlier me for thinking ahead :) ). It was only a couple of lines different
Also, decided to have a look at what the graph looked like with networkx
3
u/kuqumi Dec 12 '21 edited Dec 13 '21
JavaScript (golfed)
Tweet-sized (280 characters or less), to be pasted in the browser console on your input page. This one is 272 characters.
It should output
[part1, part2].3
u/AvshalomHeironymous Dec 13 '21 edited Dec 13 '21
Prolog NEVERMIND MY PREVIOUS BOLLOCKS turns out posting this made my brain work so here it is, actually working.
3
u/Yithar Dec 13 '21 edited Dec 13 '21
So not the most efficient or elegant solution, but efficient enough that Part 2 doesn't time out. Solution in Scala.
I say not the most efficient because I used a backtracking algorithm, which theoretically runs in O(2N * N). There's 2N-1 - 1 possible paths in the graph and N - 2 possible intermediate nodes (so it takes O(N) time to build a path). I think the key to keep in mind is that the solution set is a very, very small subset of all possible paths, which is on the order of 1013 .
3
u/compdog Dec 13 '21
Javascript [Part 1] [Part 2]
I hate graph traversal problems.
Part 1
I solved part 1 by accident. I originally implemented a memoization-based optimized search algorithm, that was actually completely broken and would result in missing and incorrect paths. Fortunately, I had a typo
!visitedinstead of!visited.has(from)which resulted in the memoization code being completely bypassed. That caused the entire cave to be searched the hard way, which yielded correct results.Part 2
For part 2, I tried to "simplify" my existing code by creating a complex inheritance-based data structure. This was supposed to allow for "temporary" memoization that could efficiently handle the changing paths involved with this problem. Unfortunately, that became too big and complex so I threw it out and desperately tried another brute-force approach. Fortunately, that worked. Even on my 10-year-old laptop, all 98K paths can be generated in about 3 seconds.
3
u/cloud08540 Dec 13 '21
Python
Today's problem gave me a little more trouble than I hoped it did. Part one was easy enough as a depth-first search. When I got to part 2 I knew what I had to do, but wondered why it took me so long to change my visited set into a visited dictionary that keeps track of how many times the node is visited...
https://github.com/danielgaylord/coding-exercises/blob/main/Advent%20of%20Code/2021-Day12.py
3
u/pstanton310 Dec 13 '21
Part 1 solution in java
https://github.com/philDaprogrammer/AOCday12
As some one has mentioned in the thread, the algorithm is not optimal and runs in 0(2^n) time since every possible path is computed. You could probably achieve linear / polynomial runtime with BFS, but requires more work
3
u/s3aker Dec 13 '21
Raku solution.
Part 2 is slow.
Tests included.
3
u/sappapp Dec 13 '21
Python. This one took way longer than it should have...
3
u/ignurant Dec 13 '21
I found this to be a great way to learn and improve recursive functions. I still have a ways to go, but I got there. Barely!
Ruby @ github
3
u/JustinHuPrime Dec 13 '21
x86_64 assembly
Part 1, Part 2
After having been defeated yesterday, I returned to it today to solve it in assembly.
These are essentially direct translations of my previous Racket solution, but I got to cheat the string comparisons by realizing that the strings:
I ran into trouble with endianness and with a plethora of logic bugs, and my solution is a lot slower than any of my previous solutions, at 6.25 ms for part 1, and 175 ms for part 2 (on a Ryzen 7). This is probably because I don't have a malloc function - I'm using the brk system call instead, which is very inefficient. If we get more of these, I might rewrite my alloc function into a proper, if leaky, malloc.
3
u/Skyree01 Dec 13 '21
PHP
Here I should have made a graph, instead I went with an array of paths. This is not a good way of doing it as it's very slow. About 5 seconds for part 2.
Basically every time I reach the end I increment the index for the next path (it keeps n partial paths in memory where n is the number of intersections met for the current branch).
When a dead end is met, the current path is removed and the index does not change.
Part 1
Part 2
There's just one line changing for the part 2: the condition to skip a small cave if re-visiting it will result in more than 1 duplicate
3
u/baer89 Dec 14 '21
Python
Recursion makes my brain hurt!
Part 1:
Part 2:
3
u/horstg99 Dec 14 '21
Python
Part 1 and Part 2
...hardest day for me...
3
u/-WorstWizard- Dec 14 '21
Rust Solution
The LMap struct is a (bad) map struct I made for extra practice that just does linear searches to find things. BTreeMap does the same but much better and faster.
The whole solution is a bit cryptic on this one, I couldn't explain it terribly well in comments without going overboard. It's fine though, it's not like it's necessary that other people can read it ;D
5
u/Mathgeek007 Dec 12 '21
Excel: 8440/9004
VIDEO OF COMPLETION
Hi. Imagine this sentence is about forty minutes of throat-scratching screaming. Take your time to imagine that. I'll wait.
No, seriously. This is important.
Visualized it yet? Got a good understanding of my pain? Okay, let's continue.
Step 0: Realize no large cave connects to another large cave.
Step 1: Get a list of every non-repeating combination of lowercase caves.
Step 2: In between every two lowercase caves in every combination, count the number of ways to get from the first cave to the second. This would be 1, 2, 3, or 4 ways, depending on if they connected through big caves or not, or directly to each other.
Step 3: In every combination, multiply those numbers together.
Step 4: Add together all the resultants from every combo.
Step 5: Read part 2.
Step 6: Cry.
Step 7: Repeat Steps 1-4, but with an extra small cave, who you manually rename to every other possible cave in every combination.
Step 8: Get the wrong answer.
Step 9: Test with sample inputs.
Step 10: Decide to try removing duplicates from the sections, even though you alr- wait, did that work?
Step 11: Get the correct answer... somehow.
Step 12: Realize it's 4 in the morning and you only started this exact line of thinking about two and a half hours into your solve.
Step 13: See Step 6.
2
u/Rascal_Two Dec 12 '21 edited Dec 12 '21
Python (135/46)
First time in the top 100 this year!
Very much a brute-force DFS solution, simply keep on adding caves to the path until the end is reached.
Part 2 actually takes something like 10 seconds, so I thought I had created an infinite loop - but nay!
Unoptimized
Optimized
As usual much to cleanup, optimized the edges into a dictionary of origins to destinations, and the rest of my data structures into the stack itself to get it down to 2 seconds to run - even was able to make it generic enough to support
Nsmall cave revisits.2
u/bboiler Dec 12 '21
python 154/87
2
u/_Scarecrow_ Dec 12 '21
Python 75/238
Psyched to get on the leaderboard on a 2 digit day! Disappointed that I botched my time on part 2. I was adding the current cave to the history regardless of whether or not it was big or small, which messed up my check for the repeats. Oh well, still happy with how it went!
2
u/dark_terrax Dec 12 '21
Rust
2611 / 1548
Did fairly straightforward dumb brute force, with nothing clever for efficiency, but part 1 + 2 still runs in under 2 seconds in release.
https://github.com/galenelias/AdventOfCode_2021/blob/main/src/day12/mod.rs
2
u/fwoop_fwoop Dec 12 '21
Racket 8.2
Full Code for both parts
My code didn't have to change too much from part 1 to part 2, the main difference was using a count map instead of a set and writing the new rules to see if I could travel to a given cave.
2
u/Heleor Dec 12 '21
First time on global leaderboard, #77 on part 1. JS/Node.
https://github.com/Heleor/aoc-2020/blob/80020f0b481b63bca3856640cb7ccf8a063c474a/2021/sol12.js
Part 2 was embarrassing. I was trying to solve a much harder problem and need to read the question.
https://github.com/Heleor/aoc-2020/blob/master/2021/sol12.js
2
u/Biggergig Dec 12 '21 edited Dec 12 '21
C++
700ms7ms5.5msGod I can't figure out how to get it faster :(After advice and changing my adjacency list to vectors for O(1) lookup, and using a bitset for visited, code now runs in 7ms!
Changing from recursion to a stack based approach lowers it to 5.5ms, by avoiding function call overhead!
OLD CODE:
2
u/phil_g Dec 12 '21 edited Dec 12 '21
My solution in Common Lisp, 2335/2041.
Since I happened to be awake when the problems released, I tried to optimize for time. So for part two, I copied and pasted my code for part one and then modified it, rather than trying to make my part one code more generic.
I made a lot of use of FSet. The bulk of the algorithm is a recursive function that has a list of partial paths and complete paths. At each step, it picks a partial path, checks to see if it's complete and, if it's not, gets the available targets for its last element, uses them to generate new paths, and adds the new paths to the set of partial paths.
The paths are FSet sequences, which means they can share structure for memory efficiency. (Native lists could do that, too, but I'd have to build them in reverse. I might switch to lists later to see if they allow for faster processing.) A breadth-first search traditionally uses a queue for its in-process paths, but I figured a set made just as much sense.
I predict lots of graph visualizations today. Here's a basic view of my cave system, without even differentiating between large and small caves. (It's late; I should go to sleep.)
Edit: I cleaned up my code. Parts one and two now share the same solution code. Also, I switched from a number of FSet structures to native lists, cutting the runtime from 6 seconds to about 1.5 seconds. I still use FSet in a few places where I genuinely need sets (or a map).
2
u/maneatingape Dec 12 '21
Scala 3 solution
With all the BFS recently I was wondering when we would see a DFS/backtracking problem!
2
u/RoughMedicine Dec 12 '21
Rust
Created a
Graphclass that wraps an adjacency list. The recursive function uses a set to keep track of the nodes and clones it for every recursive call. There's certainly a more efficient way of doing this, but I think this looks good.Solutions in Rust and Python for previous days on GitHub.
2
u/CobsterLock Dec 12 '21
C#
I was struggling for a while to figure out how to maintain the path without tons of allocations, i was thinking of storing the path of some sort of queue that you add to then pop as you go through the path. Maybe that would have worked if i was taking a recursive approach? not sure, maybe I'll revisit that tomorrow with a fresh mind
2
u/JaegerMa Dec 12 '21
ABAP
Github
2
u/giftpflanze Dec 12 '21
Factor
2
u/rabuf Dec 12 '21
Common Lisp
I'm very unhappy with my part 2 solution. But it's late and I have to drive 2 hours in the morning so it is what it is. I liked my part 1 solution though.
Mutation happy, sure, but it's pretty clean overall. When a small cave is visited it is removed from the set of caves. My part 2 added 2 extra parameters and 3 extra cases on the
cond.