r/adventofcode • u/daggerdragon • Dec 15 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 15 Solutions -🎄-
--- Day 15: Chiton ---
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:14:25, megathread unlocked!
56
Upvotes
6
u/pimpbot9000k Dec 15 '21 edited Dec 15 '21
Python and Dijkstra's algorithm.
It took me a while to figure out how to update values in the priority queue. I used
PriorityQueueand instead of updating values, I just pushed a new element to the queue and when popping the queue I ignored the elements that were already visited.EDIT: Afterwards I realize that this is redundant due to how the "network" is connected, the algorithm never finds a "better route" to an individual cell meaning if a distance to a cell has been relaxed from infinite value to finite value, the distance is never relaxed again.
Using the aforementioned fact, one can implement a simplified version of the Dijkstra's algorithm.
In the code, the
relaxedarray keeps track if the distance to a cell has already been relaxed from infinity to finite value. If the cell has been "seen" or relaxed once, there's no need to try to relax it again.Using this simplified version (and
heapq) part II took less than a second to compute....after this task, I'm worried that AoC is reaching a difficulty level that is going to trigger my Data Structures and Algorithms PTSD. This is my first year doing AoC so I don't know what to expect.
9
u/jayfoad Dec 15 '21
Dyalog APL
11
u/leijurv Dec 15 '21 edited Dec 15 '21
Python, 404th place, 78th place
I am quite annoyed at this problem because this is how I would write it if I wanted it to be a trick question.The problem doesn't say which ways you can move. It just says you can't move diagonally. Additionally, the sample input only has moves down and right.Lowest cost path from corner to corner with only down and right moves is a problem I've seen before, because it can be solved with a simple recursive memo. That fits perfectly with just saying "you can't move diagonally", and it fits with this sample input.Allowing moves in any direction then needs something like Dijkstra.I am quite annoyed that it was not stated explicitly that you can move in any direction, and that the sample input did not have any moves upwards or leftwards.Regardless.edit: strikethrough because complaining shouldnt go here
Screen recording https://youtu.be/c3iNPN5lOtg
Part 1
Part 2
4
u/[deleted] Dec 15 '21 edited Dec 15 '21
Perl
Part 1
Part 2
4
u/mctrafik Dec 15 '21 edited Dec 16 '21
JavaScript. 53ms for part 2.
Same as lot of other folks here: DP. Iterate. Assume you have data. Algorithm:
4
u/atomated Dec 15 '21 edited Dec 15 '21
Python with a Q-Learning algorithm. This implementation works for the test case in part 1, but takes way too long to be practical for actually solving part 1 or part 2. Just something different.
The code can be found here
4
u/mzeo77 Dec 15 '21 edited Dec 16 '21
Python fitting in a tweet
3
u/raxomukus Dec 15 '21
Today I like my solution!
Python
On github
3
u/__Abigail__ Dec 15 '21 edited Dec 15 '21
Perl
I used a BFS to find the path (Dijkstra). To handle part two, I didn't increase the datasctructure for the cave, instead, I made a method which returns the right value. The method returns an undefined value if the given coordinates are out of bounds, or if we have visited the cell already:
To keep track of the best paths so far, I use a heap. The heap stores 3-element arrays: an
xandycoordinate, and the minimum risk of getting to that point, and initialized with one element:[0, 0, 0].To find the path, I used the following method:
And then:
Full program including code to deal with heaps, on GitHub.
3
u/skidadpa Dec 15 '21 edited Dec 15 '21
Here's a solution in AWK (also on GitHub, part 2 merely expands the cave array first):
3
u/edub4rt Dec 15 '21 edited Dec 16 '21
Nelua
Day 15 p1+p2 under 20ms:
https://github.com/edubart/aoc/blob/main/2021/day15.nelua
A* using heap queue and with some simplifications.
3
u/huib_ Dec 16 '21 edited Dec 19 '21
Special credits to Edsger Dijkstra, a man from my home town Rotterdam who helped me out with working out the algorithm!
Python 3.10: paste of code
2
u/PartMan7 Dec 15 '21 edited Dec 16 '21
JavaScript using A-star; heuristic was simply data[0].length-x + data.length-yEdit: Added in URL; https://pastie.io/bfelpd.js (ignore the exports thingy; input is the string with the data)
Was super happy with how fast it did both parts of the example, but then part 1 took 1.6s and part 2 took 76s, so now back off to the drawing board for that sub-second attempt
Edit: Huh, only including down and right as possible neighbors dropped the runtimes to 0.9s and 69s. Still searching for some thing better to optimize...
Edit v2: Well that wasn't reliable, so discarded it. Time to look for a whole new algorithm
Edit v3: YEET USING A PRIORITY QUEUE IN THE SAME ALGORITHM HIT 483ms :D
2
u/r_so9 Dec 15 '21 edited Dec 15 '21
C
Using a PriorityQueue (from .net 6)
Link to Paste
2
u/silverben10 Dec 15 '21 edited Dec 15 '21
Python solution using Djikstra.
Part 2 took my laptop over an hour to crunch through, so I was wondering if anyone could point out some things I could do to optimise my code? I feel like it shouldn't have taken so long but I'm not sure what to fix.
Code
2
u/r_so9 Dec 15 '21 edited Dec 15 '21
F
Immutable, except for the priority queue. Runs quite a bit slower than the imperative C# solution
Link to Paste
2
u/schovik Dec 15 '21
Haskell
First I naively implemented it as DFS which was working until it does not. For the bonus, I reached performance issues. With flipping into BFS it is almost "instant"
2
u/Zealousideal-Pen9091 Dec 15 '21 edited Dec 15 '21
Here is Dijkstra algorithm based solution with an implicitly defined board for part 2:
2
u/Crazy-Maintenance312 Dec 29 '21 edited Dec 29 '21
C# (Github) (Currently only Part 1)
Smart me thought:
It may needed a bit more work to get it to acually work.
Now it's an ugly hack, but it's my ugly hack.
17
u/jonathan_paulson Dec 15 '21
22/187. Python. Video of me solving.
For a while I assumed you could only go right and down. This worked for part 1 (!) but not part 2. Did everyone's inputs have that property?
I also struggled for too long to code Dijkstra's :( It's more algorithmically tricky than I expected from advent of code!
17
u/mebeim Dec 15 '21 edited Dec 15 '21
79/62 - Python 3 solution - Walkthrough
Oh yeah baby, second day of the year on the global leaderboard! Apparently when it comes to plain and simple Dijkstra I can get the job done pretty fast. Not much to say, simple problem and simple solution. Thanks Eric for letting us rest after yesterday's P2. Could have done better for P2, lost one or two minutes because I did two
range(5)instead ofrange(4)to add tiles to the grid and ended up with a grid of 6x6 tiles, haha.15
u/CCC_037 Dec 15 '21
Rockstar:
Part 1:
https://pastebin.com/buhKd1HL
Part 2:
https://pastebin.com/Ah5AAXQ2
9
u/MrPingouin1 Dec 15 '21
Minecraft commands : https://github.com/MrPingouinMC/aoc2021/tree/main/sol/day15
It takes 2 seconds for part 1 and 2min30s for part 2.
8
u/morgoth1145 Dec 15 '21 edited Dec 15 '21
Python 230/83
I already had Dijkstra's shortest path coded in a helper library, so I just had to remember how to use it and throw the grid at the algorithm. Well...in theory. In practice I had bugs to fix! (I originally wrote it in go in 2019, then converted to Python, and I clearly never tested it!)
I also messed up by using
yas the link cost rather than the risk value initially. That's a dumb typo. That and the above bugs to fix cost me the Part 1 leaderboard.Part 2 was an interesting twist though. Dijkstra can handle it well enough (though I really need to turn it into A* with a heuristic), most of the time was me just figuring out how to cleanly extend the grid and generate the graph for the algorithm to search without having to redo everything.
Edit: Holy crap and my Dijkstra implementation continually re-sorts the queue instead of using a heap?! What was past me thinking??!!
Edit 2: Refactored to be less horrible. At least a little bit less horrible. I expect I'll return to clean it up more in the morning.
8
u/SuperSmurfen Dec 15 '21 edited Dec 15 '21
Rust (1271/510)
Link to full solution
This day was just about implementing a shortest path algorithm. The easiest one to implement imo is Dijkstra Algorithm. A good implementation requires a priority queue which thankfully exists in Rust's standard library as BinaryHeap. In fact, using it to implement Dijkstra is even an example in the official docs, which I more or less followed to quickly implement it! BinaryHeap is a max heap, so I store the negative cost in the queue:
For part 2, why make things complicated? Just create the new graph and use the same algorithm from part 1 on it:
Not really optimized but finishes in
31mson my machine.8
u/relativistic-turtle Dec 15 '21
IntCode
A*-search (...I think? I'm a little unsure of the exact definition). Djikstra's ;).- Take a current position from the search queue (Start at the top-left position).
- At every step, put unvisited positions next to the current into the queue.
- Maintain the order of the queue so that the position with lowest risk is at the top.
It can be proven that when we visit any position with this procedure we do so with minimal risk.
Note: More memory consuming today. The IntCode VM need to support ~1M integers. Also computationally heavy. On my laptop: 8 minutes for Part 2.
7
u/MasterMedo Dec 15 '21
Python 232/353 featured on github
Annoyed at myself for not reading the task properly. The numbers wrap around to 1, not 0, spend good 5 min on that.
7
u/zapwalrus Dec 15 '21
Python 940/740
7
u/[deleted] Dec 15 '21
Nim
I had a lot of fun implementing A* which is something that I have never really done myself, it was a lot of fun getting it to run how it should :) Using the red blob games guide to really learn how A* works as before I've only used simpler path finding.
I really enjoyed doing this, and one thing that I'm appreciating more and more is just how flexible and nice nim is to work with. Often it feels like I can just write whatever and then implement it to work nice and with types, and it makes it so easy to make interfaces that I can easily read and use afterwards.
To make /u/MichalMarsalek proud, this time I actually implemented
[]for grids using points, and also had some fun with other operators, it really makes for code that is easier to read and use :) so thank you again for pointing that out to me last time:)https://github.com/sotolf2/aoc2021/blob/main/day15.nim
6
u/delight1982 Dec 15 '21 edited Dec 15 '21
Trying out Python this year and I like it a lot. I had to google the dijkstra algorithm this year too:
6
u/[deleted] Dec 15 '21
Python with skimage.graph.MCP. MCP stands for Minimum Cost Path.
6
u/ankitsumitg Dec 15 '21 edited Dec 15 '21
Simple Python solution using PriorityQueue (Dijkstra Algo): GIT Link
And as always, we can go in all 4 directions not just down and right. Any improvements are appreciated, you can make a pull request for changes.
⭐ the repo if you like it. Do follow. Cheers. Keep learning. 😊
6
u/GaloisGirl2 Dec 15 '21
COBOL 6-hour Dijkstra.
6
u/Wilczeek Dec 15 '21
This one was frustratingly difficult to code properly in Powershell. Implementing Dijkstra in a naive version was fine with the test input, but with the proper input the speed went down to a crawl. So I ditched working with PSObjects and arrays, replacing them with hashes. With that in mind, part 1 completes in ~5 mins due to slow hash sorting (I couldn't figure out the better way to select the next step). I'm afraid Part 2 is beyond my skills.
https://gist.github.com/Wilczeek/b9f255e55909b2944a8e2e7c5378117b
5
u/constbr Dec 15 '21 edited Dec 15 '21
Javascript 119/362 @ 05:48/25:04
My solution today probably looks nothing like anything on this thread. I know nothing about Dijkstra (only the name of the guy), but what I did code recently at work is a Levenshtein distance algorithm.
So I looked at puzzle text and I thought: "What if I make a risk matrix and then go top to bottom, calculating minimal risk for every target position as minimal risk from possible previous positions + map risk?". Very DP-style, I guess. But that worked wonderfully, for part 1 at least.
While I was doing part 1, I thought, well, I'm lucky I didn't have to go up or left, probably that's what part 2 is gonna be about. And it was! 😂 So I quickly wrote a sort of "single-step backtracking function" and if it found new paths, well, I'll just recompute whole matrix from scratch then.
Works reaaaaal slow, but still, in a few seconds, it gives right result, and it's enough for AoC!
Maybe now, I'll figure out how Dijkstra works, thanks to other people's solutions posted below…
Github part 1 part 2
UPDATE: So I took some time to implement both Dijkstra and A*. I also optimised both by making an always-sorted list (elements inserted into the right position, head is always the lowest).
Strangely, my Dijkstra runs about 50% faster, although I expected A* to be faster as it optimises the path.
I tinkered with the implementation, but I only managed to make it even slower. I checked the number of steps both take to the result, and the difference is pretty small. My guess is the puzzle input simply doesn't favour A*'s features and increased complexity only slows things down.
Github Dijkstra A*
5
u/vulpine-linguist Dec 15 '21
C
Looking at what other people have done, my first reaction was "OH!" — i had entirely forgotten about Dijkstra's algorithm. My approach may be naïve, but it runs in 80ms on my M1 mac mini for both parts combined.
5
u/Diderikdm Dec 15 '21 edited Dec 15 '21
Python:
5
u/Melocactus283 Dec 15 '21
R / Rlang
Cheated it out with igraph because why not
5
u/6f937f00-3166-11e4-8 Dec 15 '21
Rust has the solution as example code in the docs for BinaryHeap :)
https://doc.rust-lang.org/std/collections/binary_heap/index.html#examples
5
u/j-a-martins Dec 15 '21 edited Dec 15 '21
Matlab
GitHub [Source w/ comments]
5
u/TommiHPunkt Dec 15 '21
Matlab:
I just bodged something together using the first method I could think of to create the graph. Turns out using a 250000x250000 adjacency matrix and indexing about a million times into that is a bad idea.
Using
spallocto preallocate the space for nonzero elements speeds it up by about a factor of two, so that's nice.It works, because matlab sparse array magic, but it takes about 100 seconds to get to the point where you can run the path finding for part 2. Finding the shortest path only takes about 30 additional ms. Matlab warns that this method of indexing into the sparse array is inefficient, but I couldn't figure out a better way in the time I have right now.
5
u/Gravitar64 Dec 15 '21 edited Dec 15 '21
Python 3, Part 1&2, 1.3 Sec. (sic!)
Used a dictionary to store the coord:values. So it's very easy to check the valid neighbors (if neighbor in grid). Used dijkstra with heapq like everybody to find the path with the lowest risk.
5
u/lukeredpath Dec 15 '21
Like I'm sure a lot of others, with no formal CS background, today's needed a bit of research but before long, I was writing my first ever implementation of Dijkstra. Here's my final solution in Swift - my first attempt was using a Set which had terrible performance (part 1 took nearly a minute). I refactored to use a heap-based priority queue which got it down to 0.17s for part 1 and 14.79s for part 2. https://github.com/lukeredpath/AdventOfCode2021/blob/main/Sources/AdventOfCode2021/15.swift
5
u/AtomicShoelace Dec 16 '21
Python solution using A* search with best-case heuristic being all 1s to the exit:
4
u/rukke Dec 15 '21 edited Dec 15 '21
JavaScript [730 / 895]
EDIT: removed unnecessary double check of
map[y]?.[x]4
u/HAEC_EST_SPARTA Dec 15 '21
Erlang
Solution on GitHub
Yay, pathfinding! I was looking forward to this year's first true pathfinding problem, since I thought that it would serve as an excuse to finally break out the
digraphmodule in the standard library...which turns out to be too limited to be useful for effectively any pathfinding problem with edge weights other than 1.This limitation did give me an excuse to implement Dijkstra's algorithm from scratch, which was fun; it also allowed me to play around with the
pqueuelibrary, which is very convenient although also imposes its own set of constraints that require the user to have a good amount of foreknowledge about the data they plan to insert into the queue. Since I didn't have that for this problem, I chose a pessimistic heuristic that doesn't seem to impact performance much for the data sizes we're dealing with here.4
u/cetttbycettt Dec 15 '21
R / baseR / Rlang
Here is my solution. It is not very good yet (13 seconds for part 2) but it gives the right solution.
The full code is on github
4
u/Mathgeek007 Dec 15 '21 edited Dec 15 '21
EXCEL: 1606/3817
VIDEO OF SOLVE (Probably still processing. It's only half-uploaded as I post this comment.)
Essentially, start with the bottom right number being 1, every other number being 10 million. Then, for every number on the grid, look at the four neighbours. If one of them, plus the severity number of the current cell, is less than the current cell value, make the current cell that value. Then iterate about 250 times. Worked like a charm, only took about an hour of processing. That isn't a joke. I built my equations, then needed to let Excel think for nearly an hour.
We're pushing the limit of what Excel is really capable of doing.
But we haven't broken that limit yet!
4
u/e36freak92 Dec 15 '21
AWK
First time implementing Dijkstra, don't have access to fancy priority queues or anything so it's rather slow, but gets the job done. Fun problem, learned a lot
4
u/polettix Dec 15 '21
Raku solution, takes way too much time (~ 9 minutes in my VM), it's time to take a closer look to my A* implementation! Happy to see that at least it works...
4
u/gyorokpeter Dec 15 '21
Q:
4
u/[deleted] Dec 15 '21 edited Dec 15 '21
Pure Java
I was wondering if anyone else took this approach: Instead of pathfinding, calculate the lowest risk for each square. Keep passing through the map, checking with neighboring squares if the risk can be adjusted. When you don't find any more options to lower the risk for a square, you find the solution in the bottom right square.
UPDATE: Part 1 bug fixed
4
u/semicolonator Dec 15 '21
Python, 22 lines
Using
networkx.grid_2d_graphandshortest_path_length. I interpret the risks as edge weights of all the edges that lead to a certain node. What cost me a long time is realizing that you have to pass aDiGraphtogrid_2d_graph, otherwise it does not work.4
u/e4ds Dec 15 '21
Python day 15 solution (GitHub) using Networkx for graph algorithm and Numpy for building the bigger grid.
Solutions to other days available in this repo
4
u/anothergopher Dec 15 '21 edited Dec 15 '21
Java part 2, runs in about 35ms. Only uses a one dimensional array for state just because. Naively calculates rows by row, but backfills best found routes into the rows already processed as it goes, overwriting any larger risk routes.
No need to track caves already visited, since if you cross your own path during the backfill, your tracked risk will always be greater than the risk already stored for that cave, and the backfill will abort.
4
u/codefrommars Dec 15 '21
C++
Quick and dirty Dijkstra.
4
u/kolcon Dec 15 '21
Python numpy networkx : https://github.com/LubosKolouch/AdventOfCode_2021/blob/main/day_15.py
4
u/jdaoc Dec 15 '21
Go/Golang
4
u/something Dec 15 '21
Python one liner. Today was hard without using while loops or recursion (stack overflow). Here's all my submission https://gist.github.com/JakeCoxon/cf818f658a303e77c04c312bc04498fe
4
u/azzal07 Dec 15 '21 edited Dec 15 '21
Postscript, PS... What a day!
I used Dijkstra's for the path finding, but didn't care implementing a priority queue (it's stack based, not heap based language), so I just kept the minimum costs in a dict and linearly scanned to find the minimum.
So obviously the slowest day so far Ps ~16 s and Awk ~20 s on my machine and input.
Awk, can't recommend
Ps.
mawkrefuses to run this because of thedeletein for-loop's increment expression. I'm not even sure that should work, butawkandgawkhad no problem with it. But who cares, it's not like this is production quality either way.4
u/tomribbens Dec 15 '21
Python with numpy and networkx solution on my Github.
This morning I had code that correctly calculated the sample, but didn't correctly calculate on my input. I think it was because I made the assumption that I would only go down or right. I changed that code to also go up and left, keeping track of when I would arrive somewhere I was before, but that code never stopped calculating. Then I had to go away for the day, so I had hours to think about it while not at a computer, and figured my solution was bad, and I could also import it into networkx, which I had seen a couple of days ago was an interesting module, that I hadn't used yet.
So I started reading up on how networkx worked, and how I should insert my data into it, and got it to work. That made part two almost free, as I was already using numpy to easily read my input file, so making the map 5x as big in each direction was rather trivial.
I'm still learning all of this, so I'm probably using things wrong, and so really still welcome comments on how my code could be improved.
4
u/_Heziode Dec 16 '21
Ada
This is an Ada 2012 solution:
I have used the Uniform Cost Search version of Dijkstra's algorithm.
4
u/TiagoPaolini Dec 27 '21 edited Dec 27 '21
Python 3 with NumPy and A* and Dijkstra’s algorithms
This puzzle took me long because it was my first time with pathfinding algorithms, and I needed to learn the basics and also figure out how to implement. I am going to explain how it works, maybe this can help others in future who stumble upon this puzzle.
When looking for hints about this puzzle the two algorithms, the terms "A* Algorithm" and "Dijkstra’s Algorithm" popped up a lot, so that gave me a direction on what to search for. In the end I have implemented both, but my implementation of A* ended up faster than than mine of Dijkstra. Both give the correct results for the test input and Part 1, so I got right their basic premises. I ended up using only A* for Part 2.
Both of those are algorithms for traversing a graph, that is, a series of nodes joined by paths. They aim to find the best route between two points. Here is how A* works:
In a more general case, you can also associate each node on OPEN with the path to get to them, which is the list of nodes traversed to get there. This way you can reconstruct the path. However in our puzzle we are just concerned with the total cost to get there.
The Dijkstra’s Algorithm is somewhat similar, but it uses a different logic to decide which nodes to check first. Here is how it works:
I think that the bottleneck on my case was the choice of data structures to represents all those elements on those two algorithms. Python examples that I saw online usually used nested dictionaries to associate each node with its links and costs. I just used a NumPy array. I needed to calculate the links on each step (add or subtract 1 to each coordinate), then retrieve its values. I guess that it can be faster if you first scan the array for all nodes, check all their links, and store the results in a dictionary. At least on my tests, a 2D NumPy array showed to be faster than nested list.
It is worth noting that for the priority queues I used Python's
heapqmodule, which is a built-in. It works on Python lists and turn them into "heap queues". Basically a heap queue is a list in which the elements are roughly ordered in ascending order. It tends to be reliable for getting the element with the lowest value, but it isn't always guaranteed to the absolute lowest. I assume here that the speed of the implementation, when compared to a regular sorted list, is enough to justify the "close enough" result.Keep in mind that those pathfinding algorithms are a new thing to me, so what I did were certainly not the cleanest and most optimized implementations. But they work, and hopefully can help others to get started with the subject. Advent of Code is also supposed to be a learning experience :)
Code:
Visualization:
Further reading:
1
u/radleldar Dec 15 '21 edited Dec 15 '21
A fair warning against doing anything with strings in Java:
https://gist.github.com/eldarbogdanov/4175ae193d87047cf1b7c5d1e15429c0
Isn't the sample answer wrong for the second problem? It says 315, which is the shortest path if you never move up/left, but actual shortest path that utilizes all directions seems to be 309.Edit: nope, I somehow managed to generate an incorrect board that matched the correct sample answer with the bottom-right dynamic programming solution. Ignore me :)
1
u/GrossGrass Dec 15 '21 edited Dec 15 '21
Python, 334/270
Had to do a little scrambling to add some more custom options to my util libraries (e.g. create a directed graph from a grid), but otherwise Dijkstra comes to the rescue once again.
1
u/Biggergig Dec 15 '21 edited Dec 15 '21
C++ GOT IT DOWN TO 80MS
https://github.com/Anshuman-UCSB/Advent-Of-Code/blob/master/2021/c%2B%2B/src/day15.cpp
1
u/hamzaabamboo Dec 15 '21 edited Dec 16 '21
This is my solution for finding the sum which resembles this DP problem with a slight twist that you can go up and left. However, my first run the answer wasn't correct. Out of nowhere, I just had some big brain moment that I'd just loop it some amount of times so that it converges to some value. Baam, it works. But why ? Please let me know if anyone have an idea
The code is in python. here
1
u/bumba_coder Dec 15 '21
I feel today's puzzle description is vague. I considered only right and down movements which gave me a star for Part 1 however puzzled a lot with the wrong answer for Part 2 with the same assumption. Realised that actually you can move in any direction (top, right, down, left) which is not clearly mentioned in the description.
Here is my solution for Part 2 using Dijsktra.
https://github.com/prmondal/Competitive-Coding/blob/master/AdventOfCode2021/day15-2.py
1
u/tuvang Dec 15 '21 edited Dec 15 '21
Julia
Implemented A* Pseudo code from Wikipedia. 0.48 sec runtime for part 2
Edit
Hah... Actually A* isn't an improvement over Dijkstra because Heuristic function is practically useless as it has to assume every path has length 1. You can convert this to Dijkstra by changing the heuristic function to
h(x::CartesianIndex{2}) = 0paste
1
u/kupuguy Dec 15 '21 edited Dec 16 '21
Here's my Python solution. I also added a couple of lines to print the path that was actually taken. For the full part 2 path you need a very small font indeed.
https://github.com/kupuguy/aoc2021/blob/main/src/day15.py
Also as a Jupyter Notebook with the paths shown:
https://github.com/kupuguy/aoc2021/blob/main/day15.ipynb
1
u/uglyasablasphemy Dec 15 '21
🐍️ py solution
Using a heap and without expanding the map 5 times:
1
u/Data-scientist-101 Dec 15 '21
I'm struggling on part 1. I get the right answer for the example cave, but not for my data. I have gone over the code multiple times doing the calculation manually on smaller caves and don't see the error.
Anyone provide insight into what I'm missing. If it is simple, an answer could suffice. If not, just a point to look a certain lines of code
Optimized pathing
used a hint on this one (first time :( )
got idea to do rolling sum across the entire row and column and then use 'recursion' as dynamic programming
my solution is recursion(). hint_solution() is using hint that works better
1
u/areops Dec 16 '21
Javascript
1
u/illuminati229 Dec 16 '21 edited Dec 16 '21
Python. I had to learn a bunch about DSA for this one. Definitely my longest program so far. Had something in my priority queue implementation that caused long runtimes (25s for part 1) that I had to fix for part 2.
https://pastebin.com/fjsQTnpa
3
u/SinisterMJ Dec 15 '21
C++ 828/377
https://github.com/SinisterMJ/AdventOfCode/blob/master/2021/Day_15.hpp
First time my code is running for more than a second and I have no good idea how to decrease runtime. Currently just flooding the whole board
3
u/rabuf Dec 15 '21 edited Dec 15 '21
Common Lisp
I spent more time getting the map expansion correct than the path searching.
EDIT: I threw together an A* implementation using the Manhattan distance as the heuristic (anything else risks being an overestimate). It ended up taking slightly longer to run on the input and visited every location anyways. However, if the target is anything other than the lower right, it ends up providing a significant improvement.
3
u/maneatingape Dec 15 '21 edited Dec 15 '21
Scala 3 solution
Standard Dijkstra.
EDIT: Just for fun, rewrote it to an immutable approach. Takes 10x time to run!
3
u/_I_do_not_ Dec 15 '21
Swift: Paste
3
u/paxthewell Dec 15 '21 edited Dec 15 '21
Python3. Originally I was pretty tripped up by python's heapq. Particularly because you can't modify existing entries to reduce the distance.
But then I realized that I could just push new entries instead of modifying existing. RIP memory though
EDIT: I went back with a memory profile and memory usage peaked at 59MB.
Code
3
u/aimor_ Dec 15 '21 edited Dec 15 '21
MATLAB
Just make a
digraphand callshortestpath. There's probably an easier way to convert a table of destination weights into a graph but a sparse matrix is fine. 280 ms though.3
u/DrSkookumChoocher Dec 15 '21 edited Dec 15 '21
Deno TypeScript
Some amalgamation of Dykstra's. Takes 700ms for part 2. I saw some cool stuff with a* in this thread. I'll see if I can implement that later.
The pairing function is just used to avoid lots of casting to and from strings because JS/TS doesn't have a hash-able immutable array that can be used as map keys. An alternative would have been a nested map I suppose.
https://github.com/N8Brooks/deno_aoc/blob/main/year_2021/day_15.ts
Edit: re-wrote it with a* using the lower bound of remaining risk. Now it runs in 200ms.
3
u/professoreyl Dec 15 '21 edited Dec 15 '21
Python 3
Clean code, object-oriented, type-annotated, documented.
Minimum cost solved with dynamic programming (tabulation technique).
https://github.com/DenverCoder1/Advent-of-Code-2021/tree/main/Day-15
3
u/sortaquasipseudo Dec 15 '21
Rust
I'm live-streaming my solutions via Twitch. Please stop by and help me out in the chat! Video archive is here.
3
u/tumdum Dec 15 '21
my rust solution:
3
u/Chitinid Dec 15 '21 edited Dec 15 '21
Compact Python 3 solution using networkx
3
u/flwyd Dec 15 '21
Raku, 3791/2960. Continuing to discover new ways in which Raku's aggressive type conversion makes using Pair as a data structure not so fun. I used Complex numbers as 2D positions after several days of using comma-separated strings, which worked out nicely. Naïve Dijkstra implementation was around 53 seconds on the full input for part 2, some optimizations got it in the 37-43 second range. I added an A* implementation which for some takes longer somehow[1] and also gets the wrong answer for reasons I haven't yet identified.
[1] There's a good chance it's slower because the Dijkstra implementation is just keeping track of Complex numbers, but the A* implementation is making a Map with position and cost for each candidate.
3
u/onemanforeachvill Dec 15 '21
C solution https://github.com/purport/advent_of_code/blob/main/2021/day15.c
Used a shortest path algorithm which was just gonna visit every node many times. Takes about 1 minute for part 2 :-).
3
u/sebastiannielsen Dec 15 '21
Solved it using perl, a pure implementation of djikstra algoritm, but with a little catch: Instead of looping through ALL distance values, I only loop through "relevant" values, which is unvisited values that we have "seen".
https://pastebin.com/YyJm3q7b
Works pretty fast for both part1 and part2.
3
u/surgi-o7 Dec 15 '21
ES6
part 1
part 2
3
u/icyFur Dec 15 '21
Ruby Dijkstra solution
Part One
3
u/zniperr Dec 15 '21
python3 with Dijkstra and padding the grid with 0 to avoid annoying neighbor checks:
3
u/p88h Dec 15 '21
Elixir
30ms / 952ms. For all its functional power, these kinds of problems do seem slow in Elixir.
3
u/francescored94 Dec 15 '21
nim solution short and sweet
3
u/levital Dec 15 '21 edited Dec 15 '21
Haskell
Basically a very inefficient (and not particularly functional, but fairly readable) implementation of Dijkstra's algorithm doing none of the things you'd usually do to make it faster. Was sufficient for the task though (takes about 25 seconds for both parts in sequence). It's also over-engineered in that it keeps a record of the actual path, because I thought maybe I'll need that for part 2 instead of just the cost.
Easiest improvement would likely be to filter set of nodes to visit such that any node is discarded that can not possibly be better than the current node (by using current weight + manhattan-distance for both as a lower bound).
If I remember correctly that would essentially turn this into A* Search. Might change the code accordingly later today, if I find the motivation to do so.
[Edit:] Actually the easiest improvement turned out to be compiling with -O3, which took the time for both parts in sequence down to ca. 8 seconds. Didn't know optimization flags are a thing in Haskell.
3
u/leftfish123 Dec 15 '21
Python
Finally had the reason to find out what this famous Dijkstra's algorithm is!
The solution is pretty raw - after copypasting the sample a couple of times and timing the runtime I gambled that it would run in a reasonable time for a 25x larger map and it turned out to be true (less than 4s for part 2). There must have been a more elegant way, but learning a new algorithm from scratch is enough for one day when there's work ahead.
One question I have is - would A* guarantee a proper solution? Am I right to guess that it would not?
3
u/FlyingDutchman2033 Dec 15 '21 edited Dec 15 '21
PHP using flood fill
Very lazy, quite slow for the second part but it worked
Part One
Part Two
3
u/Killavus Dec 15 '21
Rust
https://github.com/Killavus/aoc2021/blob/master/day15/src/main.rs
Pretty happy with my solution. It turns out if you abstract away cost function & neighbours you can very easily parametrize the code to work with both part 1 & 2. Runs in 80ms without duplicating cave map, 50ms with different hasher on my PC.
3
u/[deleted] Dec 15 '21
Haskell
While I did find a Haskell solution that executes in a reasonable amount of time (~13.1 seconds with
ghc -O3). I am certain it could be much faster though I've been struggling to figure out how (perhaps I need some third-party libraries)? To confirm that the algorithm I came up with is sensible, I ported it to rust and it runs in a mere ~0.16 seconds!The Rust equivalent is on Github. I'm aware it is more optimized than the Haskell version though that is because I can't figure out how to make the Haskell version faster.
How the algorithm works roughly:
maxBound.(There's probably a fancy name for this algorithm but I wouldn't know what it's called :P).
Rust
Since this isn't r/haskell I figure it's fine to just dump the Rust version here too :P
3
u/Fyvaproldje Dec 15 '21
Typescript
Simple Dijkstra, I didn't bother implementing binary heap or A*
https://github.com/DarthGandalf/advent-of-code/blob/master/2021/solutions/day15.ts
3
u/mockle2 Dec 15 '21
python, both parts, just the standard Dijkstra algorithm
3
u/toastedstapler Dec 15 '21
zig
standard dijkstra solution, completes in 16/30ms on my pc/macbook and solely accounts for two thirds of my total runtime :(
https://github.com/jchevertonwynne/advent-of-code-2021/blob/main/src/days/day15.zig
3
u/piyushrungta Dec 15 '21 edited Dec 15 '21
Nim lang
https://github.com/piyushrungta25/advent-of-code-2021/blob/master/day-15/main.nim
Takes about 100ms for both parts on my machine, 20sec to run if the input is duplicated by 50times in each direction instead of 5, ran out of memory on my machine after that. Happy that I was able to implement it without looking up the algorithm online.
3
u/danvk Dec 15 '21
Golang
https://github.com/danvk/aoc2021/blob/master/day15/day15.go
Really had to read the instructions carefully in part two: it's not
risk%10!3
u/timvisee Dec 15 '21 edited Dec 15 '21
Rust Using Dijkstra from a crate. Not super quick I guess. Not feeling too well...
Part 1 1.05ms
Part 2 37.7ms
day01 to day15 total: 40.01 ms
3
u/kateba72 Dec 15 '21
Ruby (the second time I'm posting this, because the first solution didn't work for all inputs)
I implemented A*, but I noticed that manhattan distance isn't a good metric for this problem, because it is 1/5 of the actual cost in most cases. This causes the code to visit almost all nodes either way, so I tried to come up with a better solution.
My first solution was fast, but overestimated the cost for some inputs, which led to incorrect values for some inputs, so I kept looking for a better distance estimation and found this:
Hints for non-rubyists trying to read the code:
This assigns every point on the map a value that estimates the cost from this node to the end. This value is the cost of the point plus the minimum of
This function allowed me to cut runtime from 5.2 seconds to .75 seconds and visits less than 1/10 of the points that A* would visit.
Full code here if someone is interested
3
u/skarlso Dec 15 '21 edited Dec 15 '21
Go / Golang
Explanation and blog post incoming. :)
Blog about how to do some priority queue based path finding
3
u/mschaap Dec 15 '21 edited Dec 15 '21
Raku, see GitHub.
This was the trickiest so far. Had to dust of my Dijkstra, and my initial solution worked fine for part 1 (albeit slow), and for part 2 on the example. But on the real input it was way too slow. Raku isn't really a performance beast...
Refactored and optimized things until it ran in an acceptable time. Still slow: it takes about 3m30s to run both part 1 and 2 on my input.
Note that in the examples, the shortest path always goes right and down, so a simpler algorithm might find the right answer. I don't know if that's also true for the actual input; it's definitely not guaranteed to be true: you may very well need to go up or left to go around a high-risk area.
3
u/Naturage Dec 15 '21
R
Solution here
So the good news is that apparently I came up with something broadly resembling Dijkstra on my own, only having heard the term years ago. The bad news is that I spent two hours and my code is awfully slow, not to mention - cursed in terms of arrays/lists/gods know what else used. But it runs for 12 minutes and returns a gold star, and that is good enough for me.
I'm feeling like I'm reaching the limits of my limited CS experience here, to be frank.
3
u/RoughMedicine Dec 15 '21
Python
Using
heapqfor the priority queue. Runs in about 1.5s, but I'm not sure if it should be that slow.3
u/UnicycleBloke Dec 15 '21
C++: https://github.com/UnicycleBloke/aoc2021/blob/master/day15/day15.cpp.
One of those humbling days when you realise that 40 years of software development have taught you nothing whatsoever about efficient search algorithms. It turned out I was within a long spit of Dijkstra before looking it up, so that was nice. But I so should have looked it up at 5am...
My part2 takes over 20s to run, so I'm convinced I've missed something.
3
u/mariushm Dec 15 '21
PHP
Here's the code: https://github.com/mariush-github/adventofcode2021/blob/main/15.php
Not particularly proud of it, got really lazy on part 2 and just brute forced it by making the 500x500 matrix and calculating the path like on part 1.
Part 2 takes quite a few seconds to finish and around 250 MB of memory.
3
u/jotac13 Dec 15 '21
[TypeScript] https://github.com/joao-conde/advents-of-code/blob/master/2021/src/day15.ts
3
u/sdolotom Dec 15 '21
Haskell
A super-ugly Dijkstra implementation with psqueues for priority queues. Before I took them into use the first part took ~10 sec, after that it's ~60ms, and 2.5s for the second part. I believe, there's still room for optimization, but it's enough for today.
Full code
3
u/itsnotxhad Dec 15 '21
C#/csharp
https://www.toptal.com/developers/hastebin/higimiletu.csharp
A* with manhattan distance to goal as the heuristic. This is the time I've most strongly felt the "not using my strongest language for learning purposes" effect...really would have smoked this if I were able to just
import heapq. As it stands I finally got the hang of how to usefully take advantage of C#'sSortedSetfor my priority queue. Other biggest obstacle was forgetting to keep track ofvisitednodes (the algorithm still technically works without it but the running time balloons from 3ish seconds to 30ish minutes)3
u/mstumpf Dec 15 '21
Rust, nothing special.
But got some nice animation:
https://raw.githubusercontent.com/Finomnis/AdventOfCode2021/main/visualizations/aoc2021_day15_task1_dijkstra.gif
3
u/aoc-fan Dec 15 '21
TypeScript, Under 80 line code, For me part 2 with actual input does not work without priority queue, I tried to understand why it is so, but could not figure out, any pointers will be helpful.
3
u/SpaceHonk Dec 15 '21
Swift
https://github.com/gereons/AoC2021/blob/main/Sources/AdventOfCode/puzzle15.swift
Plain old A*. Still need to add a Heap or Priority Queue to get rid of the excessive sorting...
3
u/__Abigail__ Dec 15 '21
Blog post: Chiton (Perl)
3
u/vegapunk2 Dec 15 '21
Python 3 I already knew about Dijkstra and I knew how to implement it. I simply lost a lot of time due to only considering South-East movements. I do not keep track of the visited points, I only add it to the list if the distance is lower than before. I used lists which surely slowed my solution but it still runs in approximatively 10seconds. I may try to implement it with a dictionary to see if it is that faster.
both parts
3
u/clumsveed Dec 15 '21
Java Solution
Day 15 Solution
All Solutions - repl.it
Like many, I threw together a DFS algorithm that worked great for the sample input, but after running it on the real input for about 20 minutes, the only thing I managed to accomplish was giving my laptop fan a workout.
For my second attempt, I decided to just work backward from the bottom-right and update the total risk of every node based on the total risk of it's 4 neighbors. I looped through the nodes updating their total risk-sum if a lower risk-sum could be assigned to it. I repeated that process until no changes were made to any nodes. Apparently, this is already a thing and it's called the Bellman-Ford algorithm. Learning is awesome!
I'm happy with my ~130 ms solution, but after reading some other comments here, I'm excited to brush up on my Dijkstra and A* tomorrow and see if I can implement them. These algorithms didn't come up last year, so I'm a little rusty.
3
u/No-Rip-3798 Dec 15 '21 edited Dec 15 '21
Go (no A* or Dijstra, but pretty fast!) (Edit: actually not)
Here is my code
I see a lot of people went straight at classic pathfinding algorithms today. I didn't want to take that road. Instead, I leveraged the fact that we were in a grid, and that the best path will obviously go down or right most of the time.
Obviously, this is not the most beautiful or readable code I have ever written, but it seems to run circles around A* and Dijkstra, as it completes part 2 under 100µs on my laptop.
Edit : nevermind, my benches were worth nothing as they weren't run against the actual input but the example. This code has actually "meh" performance. I feel so stupid right now.
3
u/veger2002 Dec 15 '21
I am leaning Rust with this AoC.
For this one I build the grid/map and calculate the costs for each cell from top-left to bottom down. Then I try to find better paths by iterating (and allowing to travel all directions) util the result/cost does not change anymore.
No idea what kind of algorithm this is, but it is pretty fast and it worked for both parts I and II (only repeated the grid 5x5 times for part II)
my code for part II
3
u/imbadatreading Dec 15 '21 edited Dec 16 '21
EDIT: A little refactoring and we're down to <1s runtime on my machine.
Extending the grid in pt2 took me far longer to figure out than I care to admit.
Python:
3
u/LuckyLactose Dec 16 '21
SWIFT
Used an A* implementation I had from previous years, although I had to fix a couple of bugs in it.
Horribly slow, especially on part 2 (45+ minutes when running on my phone...), definitely looking for feedback on how to make it faster.
Full repo here.
3
u/aexl Dec 16 '21
Julia
Implement Dijkstra's algorithm with a priority queue.
For part 2 generate the enlarged risk map and use the same algorithm as before.
Github: https://github.com/goggle/AdventOfCode2021.jl/blob/master/src/day15.jl
3
u/reddogvomit Dec 16 '21
Python 3.x
hello! 3-4 years at this, but I dont think I ever posted a solution - am doing it now because i didnt see anyone else solve it this way. I discovered this method after banging head against desk for hours trying to optimize my own lame heap-less implementation of dykstra.
Here's what I did:
calculate distance to each node from top left to bottom right:
** if your solution is all down and right moves, this will give you the answer straight away. otherwise:
5) flip the array diagonally (invert and mirror) (and flip your distances too) and optimize the values in steps 2-4 above. i.e. if cost[0,i] > cost[0,i-1] + distance[0,i]: then cost[0,i] = cost[0,i-1] + distance[0,i]
6) flip the array back over and work it back down toward the lower right. checking for optimizations along the edges and then the center values
repeat until you can't optimize anymore. I had to flip the part 1 input 12 times and the part 2 input 46 times (well 92 flips - optimizing in reverse, then forward directions)
https://topaz.github.io/paste/#XQAAAQAXCwAAAAAAAAA0m0pnuFI8c+qagMoNTEcTIfyUWbZjtjmBXvR+o9M0nhaSRBF/hCFNJf2dSh0N8VgtHtdI0IMxPjzmFl89ULULTeFUyCgLFnubnZ/7RPwGgcv/ikLg26moQY6RYh+w6rPQHHIZVOAaWDeAUXF3Au/YE8gx6NMot7td/PNd8ST2aQD8lR7SIqBE9ro+vVHqh0ii2SIywnkpI847O4YAHPBWdFXQlhrMtKGm8Ywk0d8NB2HC0vdsPXGWIGcgsQG8NtOUGaiV4VSaubspln1DA5UYDCjydgfJW2DSbhISM/ws2UlTiCugtMKnQEsQDzNqaXdMR585WWAT4FYVvPSthZN7c/D7+4DqXiSPok7oEYEpII230Q2kfwt1OL0ZmLwrOP9mUbddPuG/ILD9TOeNFBMVUTmRoiha9lXpjmIYC8wGSHcd0ckR5RAD7uGayC7YN+q8xTD4fOoE6E9ghIpSH7X8YlIgOjCmQdFrl/herFmW1KymcVPNpJWqnMkmywJ1FbPDHNbeF8RUd/Bbel2TXEEITTLUyigLIgvRFTry4l1i67aJZTppGEz+kBuqgHTJZflttAyrLngJbmzTIAKx4yuIcBUxokJfEG+JxbFb7G8GeFgsoPC95d5o8Qzs4lrW/LhMaE38gmOdAHJjpBHAn9wxa4QgzDyypMAZfCqekWVfl4s8hS4IY+orNwzXXGvWnYfJREDLOFZIVFOdXOLALjM5eEuZ/xhD4qoCCQQxv+SR0vHhYktH3UmXWB+rLD+XDKgXge55fkNunvHmbz+nZ1F+YZB/Kdr5E4/HlmIAD9DtrJDKQGAEBUTgMyMPb7UIxwRhDFLGkBUHOstDTJk1jpQfIpNLad8JvcMOdhfzPlwSLnVboRgtUHdjqAstS4oqALpgXbJamI764A/S2MFULSK9lk9GC/ccJ1I4xHFd50d7cH+XlHaaqpJUY7q81fYrvuf/DJ3hbRv42V+CPggWiWc63EM+/qQGFPe2kxtXGoGNZhmYZaqpqXX/1Z1mHEU/uiUJiAFbkOJst9/+qsYKu20md1iBH4U2fP8YDqR+WMlsop8BacyoEFLUUEBzAhpgxwRgWMvhHYIDv/tjZQc=
3
u/compdog Dec 16 '21
Javascript [Part 1] [Part 2]
Part 1
I don't think my part 1 solution is actually correct, but it does get the right result. It uses some basic parsing to read the input into a graph, and then runs Dijkstra's algorithm to find the solution.
Part 2
Part 2 works the same way as part 1, however I had to fix a very subtle bug in my Dijkstra implementation. When the algorithm says
select the unvisited node that is marked with the smallest tentative distance, the word smallest is apparently important. Without that check, the algorithm will work for part 1 and the test file of part 2, but not the actual input of part 2 (the result is very slightly wrong).To handle the repeating grid, I just loop through each number and "project" it 24 times into each of the mirrored positions. There's probably a better way to handle it, but this works.
3
u/AcerbicMaelin Dec 16 '21
My Python 3.10 implementation. I had to learn how to implement a priority queue using a heap for it, which was neat, and then after I'd worked that out I discovered that there's a 'PriorityQueue' implementation in the
queuelibrary that I could have used.https://pastebin.com/886A3zvH
Part 2 takes about 12 seconds on my machine (a previous version took 3.5s for Part 1, this one takes 0.11s). I'd love to know how to optimise it, given that some people have got them running in about a tenth of the time - I just can't work out what could be done to make it so much more efficient!
I'm learning with the hope of getting into software dev / data science as my next career, so if anybody happens to have any other constructive feedback on my code I'd be extremely appreciative! :)
3
u/egel-lang Dec 16 '21
Egel
with colors
3
u/wzkx Dec 16 '21 edited Dec 16 '21
Python
Very naive implementation of Dijkstra algorithm. Well, reasonable time with pypy anyway, <1s.
3
u/statneutrino Dec 16 '21
Python 3 all in numpy
I have no idea how to get something like part 2 in under a minute. I will read this solution megathread now!
https://github.com/statneutrino/AdventOfCode/blob/main/2021/python/day15.py
3
u/Skyree01 Dec 16 '21 edited Dec 16 '21
PHP
First thing I did was trying to remember Dijkstra's algorithm that I saw in school over a decade ago. At first I tried creating a graph and although it worked, it was quite slow (23 sec for part 1) so I decided to proceed from scratch.
Part 1 first version (23 sec)
Part 1 better version (0.25 sec)
Part 2 (156 sec)
Part 2 is almost the same as part 1, I don't scale up the initial input.
Instead, I check how much X and Y have been shifted to retrieve the corresponding X and Y value in the initial grid, then I just increment them, and use a modulo 9 if the increased value is above 9 so it goes back to 1 after 9.
156 seconds it still quite long but how to make it faster is honestly beyond me.
3
u/YourVibe Dec 16 '21
Typescript, Angular
code
Visualization page: https://raczeq.github.io/AdventOfCode2021/#/2021/15 (Example runs in milliseconds, as well as part1, but actual input for part2 takes about 3+ minutes, at least on my i7-4790 CPU)
3
u/stonebr00k Dec 16 '21
T-SQL
3
u/zeekar Dec 16 '21
So I first wrote a straightforward Dijkstra's algorithm solution in Raku, and it was super slow. At first I blamed the language and ported it to Perl, but it was still slow: part one took several minutes to run, and part two was still running almost 24 hours later! Of course that's entirely down to the way I implemented it: instead of creating any sort of priority queue, I was scanning through the entire set of points every time I had to pick the next one to visit - twice, in fact, first to find the lowest distance value and then again to find a point with that distance value! It was pure laziness, which stops being a virtue when it impacts performance that much.
I thought about writing in a lower-level language with a PQ implementation, but then I saw someone mention that they'd used a modified pixel-flood-fill algorithm, and the light bulb went off. So I started over and wrote the code below, which solved the whole thing in less than 3 minutes. Just for comparison I then ported this new version to Perl and Python, both of which ran in about 8 seconds. Which is a nice improvement over A DAY.
3
u/StephenBullen Dec 17 '21 edited Dec 19 '21
Excel
Trying to do every day using only worksheet functions.
http://www.oaltd.co.uk/aoc/AoC_2021_Day_15.xlsx
3
u/KT421 Dec 18 '21
R
https://github.com/KT421/2021-advent-of-code/blob/main/dec15.R
Using the igraph package, which was enough of a learning curve without having to write my own pathfinding algo.
3
u/Western_Pollution526 Dec 19 '21
C# - Late to the party - Haven't dealt with graphs since my masters so took a while to get back into it. Thanks to my fellow participants for all your contributions.
Some parts could even be reduced but at this point ID'tGaS ;)
Blah blah blah... PriorityQueue to the rescue
3
u/joshbduncan Dec 19 '21
Python 3: Took way longer than I wanted... 🤬
Code
3
u/zia_sun Dec 20 '21
Golang
Nothing elegant but uses a heap and A*
part 1
part 2
3
u/DingleJam2 Dec 21 '21
python
day15-2.py
Dijkstra, with "smart" minimum finding, so it actually finishes while I'm alive.
3
u/artesea Dec 23 '21
PHP
Part 1 Part 2
Thanks for the hints in this thread. My initial code for part 1 solved the example, but not my input. I knew straight away the problem was that moving left or up to go around a longer route would be needed, but couldn't think of an efficient way to do it.
Part 1 solves in 0.46s, Part 2 32s
3
u/ViliamPucik Dec 24 '21
Python 3 - Minimal readable solution for both parts [GitHub]
3
u/hwg434 Jan 31 '22 edited Jan 31 '22
Python - Solution without pathfinding
Not being a programmer, just someone who does a bit of scripting on the side, I find many of the AoC puzzles quite challenging. For Day 15, not being familiar with Djikstra or other pathfinding algorithms, and guessing that a brute force approach would not scale, I had to come up with something else.
I decided to flip the problem on it's side (or at least, rotate it 45), and then split it in two parts:
Consider a 4 x 4 grid:
First go from diag 1 to the middle diagonal (e.g. diag 4 above) and find the min risk for each point. The minimum risk for each point in a diag is just the minimum of the accumulated risk of the neighbors above, plus its own value So, we can just iterate through each diag, down to the middle one.
(This assumes only moving down, or down/right in the original matrix. More on that later.)
Do the same from the "bottom" (diag 7) up to the row below the middle (diag 5 in this case)
We end up with something like this, for a "min-risk" matrix:
Then, for each middle diag point, the min risk for the full path through that point is its risk from the top half + the min risk of its neighbors below e.g. diag 4, the second element risk is 4 + min[19, 13] = 17
Then the overall min risk is the min of all the middle diag min risks (17 in this case)
And you can see what the path is by following the minimum risk numbers in each diag from middle to top and bottom.
This works for the example (10 x 10), the input (100 x 100), and the expanded example (50 x 50) For me it didn't work for the expanded input in Part 2 (500 x 500), because my expanded input, like some others, had left/up moves in the minimum-risk path, not just down/right.
The kludgy way I fixed this (in the Part 2 code): after calculating the min-risks on a diag, go up one to diag N-1 and recalculate min-risk for each point considering all 4 neighbors, instead of just the neighbors above. Then go back to diag N and recalculate the min-risks there, using the modified min-risks from diag N-1. (And similarly for the bottom half)
The Part 1 code runs in ~50ms for the 100 x 100 input, Part 2 takes 2.5s for the 500 x 500 input, on my 5-year-old generic work laptop.
The simpler Part 1 code is here
1
u/jchurc Dec 15 '21
Looks like AoC website has a bug for day 15. The solution for my input data is not accepted. However I ran the same solution code against 2 other accounts' input data, and those solutions were accepted.
4
u/mcpower_ Dec 15 '21 edited Dec 15 '21
Python, 219/37. Solved the completely wrong problem for part 1 - I thought it was this classic DP problem where you could only move right and down. The sample tricked me!
Boilerplate (slightly modified to remove additional features I didn't use):
Part 1, failed:
Part 1, worked:
Part 2:
4
u/hugseverycat Dec 15 '21
Python with A* stolen from the internet (and comments)
Well, I guess one could say I am learning something because when I read today’s puzzle I was like “oh no, an algorithm I have no chance of coming up with on my own”. So I wasted no time and went off to professor google to find about cheapest paths through weighted graphs and found our old friend redblobgames.com. I read through the Implementation of A* post then shamelessly stole the code. Here: https://www.redblobgames.com/pathfinding/a-star/implementation.html
So I’m sorry to say the first half of my code is stuff I didn’t write. Well, I typed it myself if that counts for anything. But I mostly did that because I was changing a few things and I’m working on my iPad and for various reasons typing seemed easier than copy-pasting then deleting the things I didn’t want.
But the 2nd half of the code, which is all the stuff about expanding the grid, I did write! Yay me! And that’s the part I commented. In case anyone is interested.
Ugh I feel dirty
https://github.com/hugseverycat/AOC2021/blob/master/day15.py
4
u/p88h Dec 15 '21 edited Dec 15 '21
Python w/o queues; <50ms part 2 (w/pypy, actual execution is around 4ms)
2
u/hugh_tc Dec 15 '21 edited Dec 15 '21
Python 3, 413/252.
Part 2, and (edit) the cleaned-up code.
Well, I tried to be clever with networkx. It did not work out :(
2
u/ckennelly Dec 15 '21
C++, 250/91
Part 1, Part 2
2
u/seligman99 Dec 15 '21
Python, 757 / 492
I spent the majority of the time getting the puzzle expanding to work right, somehow I kept reading the whole way the modulus worked wrong, sadly.
github
2
u/nlowe_ Dec 15 '21
Go, 631/732
https://github.com/beefsack/go-astar did all the heavy lifting today, first path-finding problem this year! I already had utilities that map the input to a 2d grid of
runeso bolting on A* on top of that was fairly trivial.Very straightforward today, lost some time on an off-by-one error and had to wait a minute to submit a new answer. Part two should have been trivial but I had some trouble extending the grid properly and spent a few minutes debugging. Overall, a very fast day for me, best placement since Day 2!
2
u/death Dec 15 '21
Day 15 solution in Common Lisp.
Easy when you have an A*/Dijkstra implementation lying around.
2
u/snewmt Dec 15 '21 edited Dec 15 '21
Go 652/273
Good ol' Dijkstra. Crushed my dream of finishing each day in sub 1 ms.
I did some benchmarking and as expected it's all about the heap.
60% of the time is spent on heap.Pop (re-shuffling). Will do some experiments to see if there's a more efficient data structure for this.
2
u/Imaginary_Age_4072 Dec 15 '21
Common Lisp
My solution is above, but it's mainly a call to a Dijkstra routine I have in my utility library. The routine takes a start vertex, a function to call when it's found the shortest distance to any vertex in the graph, and a function that will provide the neighbours of a given vertex and their distances.
The second part had some nifty quotient/remainder/modulo calculation to find the risk for the expanded grid. It's quite nice that once I wrote part 2 the only thing that I need to change in the code to go between parts is the map dimension.
2
u/Sheler_ Dec 15 '21
Python (152/285)
(only for part 2, since part 1 is basically the same)
I usually post my solutions in Desmos, but my today's solution in python seems a bit interesting.
Like many, I initially assumed that you can only move left and down. When I realized that it is in fact not the case, I had no time to implement Dijkstra's algorithm, so I decided to take a risk and adapt my DP algorithm to solve this problem.
So, the idea is rather simple. First, you initialize the distance matrix as +inf (and as 0 at the starting point). Next, you just do the regular DP pass through it, but you take a minimum of all 4 directions. Repeat, until the matrix stops changing.
It took only 50 passes for it to converge, which is a bit surprising. Obviously, the runtime is terrible, but I'm just happy that it worked.
2
u/encse Dec 15 '21
C# classic Dijkstra
https://github.com/encse/adventofcode/blob/master/2021/Day15/Solution.cs
2
u/allergic2Luxembourg Dec 15 '21 edited Dec 15 '21
Python
I kept a numpy matrix of the cost from each position to the bottom right corner, and iterated on it by checking whether the best path was to each of its four neighbours, until it converged. Basically the cost matrix ends up mostly filled from the bottom right corner to the top left.
Here's the main part of the algorithm:
I was a bit surprised that numpy doesn't include a function to shift an array along an axis while padding the edge with a constant, so I wrote my own:
2
u/[deleted] Dec 15 '21
Rust
petgraphsaving this year 1 CS student who has yet to learn Dijkstra's algorithm :(Part 1
Part 2 (this disgusts me too)
Full solution here.
2
u/Pruppelippelupp Dec 15 '21
Rust.
750ms. Probably because my queue is god awful (a hashmap). Apparently I did Djikstra by accident.
2
u/JaegerMa Dec 15 '21
ABAP
Github
2
u/mendelmunkis Dec 15 '21
C
Probably the most inefficient algorithm here
11/146 ms
2
u/landimatte Dec 15 '21
Common Lisp
I already got a A* implemented in my utilities file, so part 1 was just plumbing things together -- first time rang below 1000!
For part 2 instead, I had to use my brain a little more, but apparently we both (me and my brain) was not actually ready for it:
What happened?
Anyways...
2
u/Chaosteil Dec 15 '21
Rust
First time I added a helper struct, and still keeping myself to stdlib.
2
u/pred Dec 15 '21
Python3 with NetworkX, using
nx.grid_2d_graphto avoid most of the index juggling, and as an easy way to get the head/tail of a given edge: Source2
u/chkas Dec 15 '21
easylang
Solution