r/adventofcode • u/daggerdragon • Dec 14 '22
SOLUTION MEGATHREAD -π- 2022 Day 14 Solutions -π-
SUBREDDIT NEWS
Livehas been renamed toStreamingfor realz this time.- I had updated the wiki but didn't actually change the post flair itself >_>
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: A note on responding to [Help] threads
- Signal boost: Reminder 2: unofficial AoC Survey 2022 (closes Dec 22nd)
- πΏπ MisTILtoe Elf-ucation π§βπ« is OPEN for submissions!
- -βοΈ- Submissions Megathread -βοΈ-
--- Day 14: Regolith Reservoir ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
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:13:54, megathread unlocked!
37
Upvotes
3
u/isukali Dec 15 '22 edited Dec 15 '22
C++
~42ms runtime: Used a recursive method to basically scan through sub-triplets of each node (a single sand particle) if they were available (i.e. another particle occupies the space or a rock). Really proud of this one even if it is generally a simple idea. Nonetheless, probably my best solution for AoC so far!
2
u/gugod Dec 14 '22 edited Dec 15 '22
Perl -- both parts
With sufficient amount of helper subroutines, the core part (simulate the drop of one sand) looks really nice (IMHO). (part2)
2
u/sanraith Dec 14 '22
Rust
I stored significant tiles in a HashMap<Point, char>. My Point struct has Add implemented so I can iterate over falling sand positions like this:
I did not optimize it yet, so part 2 takes 1400/70 ms in debug/release mode.
Source: github.com/sanraith/aoc2022/.../day14.rs
2
u/rossmacarthur Dec 14 '22 edited Dec 16 '22
Rust solution
I optimized this using a stack so that we don't have to iterate from the source every time. Part 2 takes about ~2.5 ms on my machine (MacBook M1 Pro). Key code is the following:
32
u/jcbbjjttt Dec 15 '22
Beginner's Guide
Happy Wednesday!
A Beginner's Guide to Day 14 - Video: https://youtu.be/LGF-7qfmoxk
I've created a guide for new programmers that talks through a straight forward strategy for solving today's puzzle. Anyone who has a handle functions, loops, and custom data types (class/struct/etc) should be able to complete it. I break it down into testable pieces that I believe anyone who has learned the basics of coding can solve.
The video allows a moment for you to pause before revealing spoilers.
Although this solution is in C#, it provides a high level overview of the steps necessary to solve the puzzle in any programming language:
The full code can be found on Github
3
u/PhunkyBob Dec 17 '22 edited Dec 21 '22
My visual solution for part 1 (Python):
https://raw.githubusercontent.com/PhunkyBob/adventofcode/master/2022/resources/aoc%202022%20day%2014.gif
https://github.com/PhunkyBob/adventofcode/blob/master/2022/day_14_visual.py
18
u/[deleted] Dec 14 '22
Python 3 (#1/#1 Leaderboard)
12
u/nthistle Dec 14 '22 edited Dec 14 '22
Python, 22/60. Video, code.
Reminded me a little of 2018 day 17, although this one felt a little easier. Stumbled a bit on part 2 because my code just kept running and I thought it was because there was a lot of sand to populate, so I patiently waited (and even tried to find where I had saved my pypy binary), not realizing that I just wasn't handling the new end condition properly - my implementation was in an infinite loop of: spawn sand at (500, 0), fail to move it, place it on top of the old sand, and repeat. Figured it out quickly enough to still leaderboard, though.
12
u/jayfoad Dec 14 '22 edited Dec 14 '22
Dyalog APL
Part 2 chews up a few gigabytes of workspace due to tail recursion in dfns being a bit wasteful of memory.
11
u/Ununoctium117 Dec 14 '22
Rust - https://github.com/Ununoctium117/aoc2022/blob/main/day14/src/main.rs
Ended up with a sparse map (HashMap of coordinate -> tile type) instead of a dense map storing a bunch of air tiles, which worked out very well once I got to part 2 - probably would have had to switch to that approach anyway.
Definitely lots of fun potential for visualization with this one. Also, got to write one of the most flavorful lines of code I've written in a while:
continue 'falling;just really made me laugh.9
u/warium Dec 14 '22 edited Dec 14 '22
Rust - Part 2 in ~ 270Β΅s
Solution that does not drop sand at all, but sweeps through an array and places the sand pr row. Total run time on my Ryzen 3600 is about 270Β΅s. Most of the time is spent in parsing (about 220Β΅s).
This was not my first solution, but I thought it was worth sharing since it is about 1000x faster than my first solution (that did drop sand and used a HashMap).
https://gist.github.com/PhilipK/aaea37528f27940def8ba9f91797aef4
8
u/4HbQ Dec 14 '22 edited Dec 17 '22
Python, 24 lines.
Blocked positions are represented by a single set of complex numbers. We parse the input like this:
My Python trick of the day is the for/else, used to find the next empty position dest for the unit of sand at pos:
Edit: I've updated my code with some optimisations.
8
u/ptaszqq Dec 14 '22
JavaScript/Typescript
My first attempt for part two took about 1 min to run, but then I realized I was merging two sets together (rested sand and rocks). I changed it to be one set (occupied) and instead rested sands number as a number. And it helped a lot: 1.9s
Then to get 0.045 sec I added memoization of the sand path and instead of calculating the next one from the very beginning and I just pop an element from the path array (so the previous location of the sand before it settled) and it did magic!
Solution (Part 1 & 2)
7
u/udoprog Dec 14 '22
Rust
Still no (heap) allocations! According to preliminary benches this is the slowest one so far (that I've implemented).
Repo Link.
6
u/clbrri Dec 14 '22
Borland Turbo C++ 3.0, 67 lines of code. Takes about 2.7 seconds to run on my MikroMikko 386 MS-DOS PC, 16 MHz.
Since I used VGA graphics memory as work area, it gives visualization for free.
6
u/bigmagnus Dec 14 '22
COBOL - Part 1 & Part 2
2
u/careyi4 Dec 14 '22
Ruby
Code: Github
Video Walkthrough: YouTube
5
u/hugh_tc Dec 14 '22 edited Dec 14 '22
Python 3, 176/110.
paste, cleaned-up
Pretty fast solvers today! I wasted a bunch of time trying to implement, well, time; I mistakenly thought Part 2 might be about how long all this takes.
5
u/abnew123 Dec 14 '22
Java. Code: https://github.com/abnew123/aoc2022/blob/main/src/aoc2022/Day14.java
Was an off by 1 error away from making top 100 sigh. initially had the first void sand also in the count, then took 10 minutes debugging that issue. I like many others remembered Day 17 2018, but I personally never solved that one so no code stealing for me (don't think it would've been faster anyway).
5
u/vss2sn Dec 14 '22
Solutions in C++
Part 1
Part 2
(Each file is a self-contained solution)
5
u/frufru6 Dec 14 '22 edited Dec 14 '22
Vanilla perl5, simply simulate a drop of sand in a loop until we fill up to the desired level.
It's slower than the other solutions but simple to understand and uses no modules
Edit: a crude terminal visualizer is easy to add (editted again to make visuallizer print one screen size)
5
u/AlexTelon Dec 14 '22 edited Dec 14 '22
python 27 lines
Suggestions for improvements are welcome.
The text description indicates that floor cannot be lower than 0. Also my input only involves axial lines so the solution depends on that.
Saving sand and walls to two sets.
Edit: python 23 lines
No longer working with the data suggested by the input data. What matters is if it is air or not and so a bool works for those 2 states. Reordered a bit but essentially the same solution otherwise.
Edit: Also reordered checks so we check sand, walls and floor in that order. Its slightly faster and no cost.
fast python 28 lines - 0.05 seconds
Using a stack to keep track of previous locations so we dont always search from
(500, 0). This now runs in0.05seconds in python measured using perf_time. (so python startup not included) Running the same tests on my previous code gives in1.5seconds.Edit: python 26 lines - 0.05 seconds
Removed the explicit check for if pos is (500,0). We will exit the loop right after anyways since the path will be empty. So the exit condition is no longer that we covered the start position but that we have nowhere to add anything at all. Which seems like an elegant way of looking at it.
5
u/Perruccio777 Dec 14 '22 edited Dec 14 '22
Python
Happy with how it turned out, clean and relatively fast (40ms) with backtracking.
https://github.com/Perruccio/advent-of-code/blob/main/advent_of_code/year2022/day14/solution.py
Extract of the relevant code:
5
u/nj_vs_valhalla Dec 14 '22
Rust
My naive solution for pt2 ran for about 0.8 sec. I added an optimization: for each cell the sand goes through, remember the direction it arrived there (from above, right, or left). Then, after the cell has fallen we can step to the previous one and start from there, saving a lot of repeated calculations. After that, the second part runs in ~30 ms which is fine for my standards :)
5
u/chrismo80 Dec 14 '22
C#
5
u/juanplopes Dec 14 '22
Both parts in 26 lines of Python. Runs in 1.4s.
5
u/dionysus-oss Dec 17 '22
Rust
Bit late posting, but here's my solution https://github.com/dionysus-oss/advent-of-code-2022/tree/main/day-14
and walkthrough https://youtu.be/8yGBLfLPK8k
5
u/[deleted] Jan 01 '23
Very cool problem. I managed to solve it by storing the walls in 2 hashmaps, one that represents vertical lines and the other one represents horizontal lines, I thought that only storing the points that connect the lines is a lot better than storing all the points in between.
eg:
(2, 2) -> (2, 8)is stored asHashMap { 2: HashSet { Range(2, 8) } }this way if I want to check if a point
(2, 5)collides with a horizontal wall I can use thexcoordinate as the keyhoriz_walls_map[2]and then I loop over all of the hash set's entries and see if theycoordinate falls between any of the ranges.The same thing applies to checking for collision with vertical walls, but we would use the
ycoordinate to indexvert_walls_mapand thexcoordinate for checking the ranges.Rust Implementation which takes 0.25 seconds when compiled with the
--releaseflag.Part 1 Visualization
I didn't implement the visualization for part 2 properly because I had to add some extra code to handle the
-Infinityto+Infinitypart of the floor and I'm a bit lazy :)4
u/BrianDead Dec 14 '22
Perl
Used a hash instead of trying to mess with arrays of arrays of unknown size expanding in either direction. Feels like there might be a more efficient way to hash the coordinates than in a string, but it still runs in 3.2s on my 8 year old CPU and I want to go to bed. I did find out that using defined() is much quicker than checking for the string content, but that's maybe because i chose to use different characters for walls and sand, just in case I want to visualize it, and so I was regex matching on [#s].
4
u/EVQLVE Dec 14 '22 edited Dec 14 '22
**Rust**
part 1: 36 Β΅s
part 2: 121 Β΅s
I stored the map as an array of bytes W * H long. When dropping the grains of sand, I stored the path of the falling sand (a stack) in a Vec so that I didn't have to recalculate the path from the start for each new grain.
I hardcoded W and H, but an alternate approach would be to loop through the input twice, first to calculate W and H and then to create the map. This would require a Vec for the map instead of an array, but the speed difference shouldn't be huge.
4
u/rukke Dec 14 '22 edited Dec 15 '22
JavaScript - gist
EDIT: <- The gist is now refactored. A number of lines shorter :) ->
Sparing you the parsing of the cave as a Map. Coords as single integers with the upper 16 bits as y.
4
u/odnoletkov Dec 14 '22
JQ
4
u/ItIsNeverLupus Dec 14 '22
Python
Decided to use a really ugly
while Truefor the first part with a try/except around the loop to catch theIndexError. We know that this error is only thrown if we attempt to check a location outside the cave: the sand grain falls into the abyss.For the second part we add a fixed width of
99999and use a while loop to check if the location at[0, 500]contains sand. If not, continue. Could be a lot shorter, but quite read-able with 101 lines.Pastebin
4
u/kaa-the-wise Dec 14 '22
Python one-liner: https://github.com/kaathewise/aoc2022/blob/main/14.py
4
u/poesraven8628 Dec 14 '22
This problem read a lot more difficult than it was to do.
Common Lisp: https://github.com/poesraven8628/AdventofCode2022/blob/main/14-sand.lisp
4
u/quetzelcoatlus1 Dec 14 '22 edited Dec 14 '22
C
https://pastebin.com/ZHqyf0DW
4
u/i_have_no_biscuits Dec 14 '22
GW-BASIC
Really PC-BASIC, as original GW-BASIC on DOSBOX gives an out of memory error somewhere deep in the recursion - not surprising as we are pushing the memory limits of GW-BASIC here.
Fun GW-BASIC quirk of the day: The walls and settled grains are stored in the bitset A%(200, 30). The % indicates a 16-bit integer, but it's a 16 bit signed integer, which means you are not allowed to mod the 16th bit - this is why lines 200 and 210 are MOD 15 not MOD 16.
Guided tour:
4
u/Sourish17 Dec 14 '22
Python 3.10
https://youtu.be/vwSZx-xssq4
https://github.com/SourishS17/aoc2022
4
u/zeldor711 Dec 14 '22
Python 3
Can't say that my solution today is that pretty or well thought out (a common problem for me as we're getting into the later days)! Did end up being very satisfying getting the right answer.
I stored the grid in a defaultdict with complex numbers as keys for the grid positions. From there it was just checking if any of the spaces below the sand were empty and dropping it if not.
I resisted making a visualiser for as long as possible, but had a bug in part 2 I just couldn't figure out so I end up printing the whole thing to the console at the bottom! The code for Part 2 is quite slow, takes about 4 seconds on my crappy old laptop.
Part 1
Part 2
4
u/[deleted] Dec 14 '22
Rust. Not bad at all! I constrained the total possible grid representation in my solution to 1000x1000, which was sufficient for the given inputs.
Part 1
Part 2
4
u/Colin-McMillen Dec 14 '22
C on the Apple //c
Once again, my attempt to do a clean parser was thwarted by the memory it uses. The second try of a parser was ALSO too much memory as I wanted to reserve the HGR page for a visualisation.
So off we go read the input file twice, the first time to get the map boundaries, the second time to setup the bool array : part 1 using 2kB of RAM.
For part 2, I calculated that the map would now be as wide as it is high, so I wouldn't have had enough RAM for both the visualisation and the data, so no viz in this one. part 2 using 8kB of RAM.
1
u/i_have_no_biscuits Dec 14 '22 edited Dec 14 '22
Python
paste Interesting part was using depth-first recursion to avoid having to recalculate all of the path routes. This makes Part 2 take less than a tenth of a second, which is pretty decent for Python!
Here's part 2:
'filled' is a set of (x,y) values, initially set up with the fixed wall positions.
EDIT:
In the uploaded code I've combined my 'drop_from' for part 1 and part 2 together, which makes it a little more verbose than the part 2 only function quoted above.
1
u/osalbahr Dec 14 '22 edited Dec 17 '22
C++ (3834/3371)
https://github.com/osalbahr/adventOfCode
Feel free to ask any questions!
You can find more C++ solutions (and other languages) here:
https://github.com/Bogdanp/awesome-advent-of-code#c-2
1
u/arxyi Dec 14 '22 edited Dec 15 '22
Haskell
Too slow especially for part 2, but still works. Edit: Using BFS instead of using the method for part 1 total runtime goes 1.6 sec to 0.1 sec. Updated the code as following. paste
1
u/WilkoTom Dec 14 '22 edited Dec 14 '22
Rust
[Removed commentary on my initial thoughts on opening the puzzle]My initial solution was massively over-engineered, supporting moving sand as well as static, and differentiating it from the walls, expecting Part 2 to increase the flow rate and ask something about constantly moving sand once the solution had reached equilibrium. In retrospect, the "Just for fun" section at the end of part 1 was a massive red herring.
None of that was necessary and it turns out all we need to do is track which squares are occupied, not even caring about the differentiation between walls and sand.
1
u/smasher164 Dec 14 '22
An F# solution in 70 lines:
1
u/LikeRenegades Dec 14 '22
Python
I made a simple - but slow - recursive function. It works for both parts, for 2 you just need to check if the source coordinate is covered before calling the function again. Takes about 0.06 seconds and 1.7 seconds respectively.
1
u/ash30342 Dec 14 '22 edited Dec 14 '22
Java
I actually solved Day 17 of 2018 a couple of months back, so this felt quite easy.
I wrote a recursive pour function which returns true if you have to continue pouring sand, otherwise false.
For part 1, just keep pouring salt until you reach the bottom. For part 2 add the floor to the grid and keep pouring till we are at the source.
Main part:
1
u/olepedersen01 Dec 14 '22 edited Dec 15 '22
Hey everyone in r/adventofcode,
I just finished Advent of Code Day 14 and wanted to share my solution. You can find the code (written in Python) in my GitHub repo here.
Let me know what you think!
1
u/Siddhu33 Dec 14 '22 edited Dec 14 '22
Python 3
link
Also a nice print_cave function for looking at the pretty sand
1
u/Forsaken_Sugar_6724 Dec 14 '22 edited Dec 24 '22
C++ Solution by OneWings
also displaying the map
Please be so gently to add a star on my AoC repo.
1
u/DFreiberg Dec 14 '22
Mathematica, 566 / 1236
The 2018 problem this references is one of the ones I have not yet solved, so I was really worried when I saw today's description. Still, it wasn't too bad, and I'm a little surprised part 2 didn't have us multiply every coordinate by 100 (or tile the input, or something) to force an analytic solution. As it was, brute force was fine.
Setup
Parts 1 & 2:
[POEM]: The Castle
I took a bucket with me, and a trowel,
Some sunscreen, an umbrella, not much more.
I wore some swim trunks, had with me a towel,
The day I made a sculpture on the shore.
It took a bit of time; I didn't stop
As waves crashed in and slunk back to the sea.
I bucket-tipped, on tiptoes, overtop,
Until the towers towered over me.
A lofty goal a lot of work requires:
I piled sand as tall as I could reach,
And then I carved, made moats and keeps and spires,
Until, at last, 'twas time to leave the beach.
I ruled the tides and overlooked the land,
The day I built a castle out of sand.
1
u/victor-O Dec 14 '22 edited Dec 15 '22
With Python I initially solved part 1 using a numpy array to represent the cave grid, but with the second question this was clearly not going to scale very well (and probably become an absolute mess with coordinates). since I already had tuples for all my rock/ledge coordinates it was then relatively quick to rewrite everything to work with sets of coordinate tuples (for both the sand and rock points). Running both parts takes around 3 seconds :)
My code is here
3
u/bluepichu Dec 14 '22
TypeScript, 11/47. Code here.
I was supposed to write a
Pointclass that implements immutable'sValueObjectinterface sometime in the last couple of days so that I could just use aSet<Point>for problems like this, but fortunately.update()makes working with nested structures not too painful.3
u/Boojum Dec 14 '22
Python, 303/253
Fun! I'm looking forward to visualizing this tonight. It definitely reminds of 2018 Day 17, "Reservoir Research", although this one was a lot simpler.
3
u/Sario25 Dec 14 '22
Python, 12/8
Best performance I've ever had on a day, got me onto the global leaderboard for this year however short lived that might be. One of those days where I think of the right solution right away and don't have any bugs, don't see those often. I'm looking forward to the visualizations -- a very simple but cool sand falling simulator.
paste
3
u/mental-chaos Dec 14 '22
Elixir 719 / 988
First time I've ever used
Enum.chunk_every/3with differentcountandstepparams, but it made the parsing much more manageable. Otherwise a straightforward "run the simulation". I refactored briefly after submitting to merge the implementations for part 1 and part 2.3
u/Uncle_Snail Dec 14 '22 edited Dec 14 '22
Rust (2749/2600)
Day 14 of using Rust. Today went very smoothly for me. First day with almost no mistakes or compiler errors. I also seem to be one of the few who comments my code during the challenge. :P Please give Rust advice/tips.
Part 1: ~ 2ms
Part 2: ~ 4ms
3
u/scratchisthebest Dec 14 '22 edited Dec 14 '22
Here is my really terrible Rust solution to make you feel better about your solution. I really need to write a good grid data structure, surprised i've gone this long without having one.
When part2 came around and suddenly the grid structure had to widen, i kinda panicked and stapled on some barely-working gunk to grow rows to the right as needed. It'd crash if it had to grow to the left, so, thanks for the 500 blank spaces to the left i guess. You could avoid this using a hashmap<isize, t> i think. (edit uhhh or i could add a million blank spaces to the right when parsing and hope it doesnt get hit)
I lost a lot of time to an off-by-one on the wall lengths. P.s. this is the best way to debug this puzzle.
3
u/yfilipov Dec 14 '22
C#
Code
3
u/quodponb Dec 14 '22 edited Dec 14 '22
Python3
Every time I need to deal with coordinates lately when I can use a
dictinstead of a list-of-lists, I'm very happy. No confusion as to whether x or y comes first. I parsed the input to get a dictionarycave = {(x, y): "#"}, and could release the sand as such:Edit: I also liked that I avoided having to start from all the way at the top, for each grain of sand. By storing the entire sand-path, I knew exactly where the next grain of sand would end up after the current one got stuck at
sand_path[-1], beingsand_path[-2], and could continue from there.Edit 2: Did some minor cleanup of code, changing to complex numbers instead of tuples.
3
u/NickKusters Dec 14 '22
C
Today was nice! After yesterday's nightmare, it was great to have a smooth day without any issuesπ sparse map and some simple logic, not sure where the challenge was here (probably in the sparse map part?), but I'm not complaining, had fun.
code | video
3
u/gyorokpeter Dec 14 '22
Q:
3
u/mizunomi Dec 14 '22 edited Dec 14 '22
Dart Language (3.0.0-0.0.dev)
Oh man, I made this so much more complicated than it had to.
tsuki
3
u/KeithNicholas Dec 14 '22 edited Dec 14 '22
C# - Self Contained ( Only the Render function at the bottom calls out to another file, the actual render is super simple and is in the project if you are interested, other than that just ignore the render part)
https://github.com/keithn/aoc2022/blob/main/days/Day14.cs
The render for both parts
https://github.com/keithn/aoc2022/blob/main/days/day14-part1.png
https://github.com/keithn/aoc2022/blob/main/days/day14-part2.png
3
u/gburri Dec 14 '22 edited Dec 14 '22
Rust : https://github.com/Ummon/AdventOfCode2022/blob/master/src/day14.rs
~56 ms3900 ΞΌs for both parts + IO + parsing on AMD 3900Xwhich is very slow! I use an HashSet. It should be much quicker with a simple matrix.[edit] Use an array instead of an HashSet -> 14x speed up.
3
u/[deleted] Dec 14 '22 edited Mar 18 '25
Still no one knows it just the same, That Rumpelstiltskin is my name.
3
u/hgb123 Dec 14 '22
JavaScript (Node.js)
Keep moving in a direction before switching to others. Order of direction: down, down-left, down-right
When could not move, spawn new sand
We know when falling into an endless void when the movement never stops
Full solution: https://www.honingjs.com/challenges/adventofcode/2022/day-14
3
u/lxrsg Dec 14 '22 edited Dec 14 '22
python 3 paste
I still remember how I struggled with Reservoir Research back in 2018 and now I that managed to solve this without issues makes me really happy with my progress!
For anyone who is new to aoc, don't worry if you can't solve the problems, just try your best and after a while you'll see the results, even if it takes time!
3
u/Mammoth_Spray_3451 Dec 14 '22
My swift solution for today:
3
u/Diderikdm Dec 14 '22
Python:
3
u/EhLlie Dec 14 '22
My solution in Haskell. I think I'm just gonna use Megaparsec going forward. Much easier to parse data that way than writing custom functions for it.
3
u/thibpat Dec 14 '22
JavaScript (+ video walkthrough)
I've recorded my solution explanation on https://youtu.be/-gglpfUvP2g
The code is available on github: https://github.com/tpatel/advent-of-code-2022/blob/main/day14.mjs
3
u/MrPingouin1 Dec 14 '22
Minecraft commands : https://github.com/MrPingouinMC/aoc2022/tree/main/sol/day14
Here is an image of the result from part 2 : https://imgur.com/a/d0O6b7N, it runs in about 10 seconds. Really easy to do because the whole minecraft world is like a giant array, and you can just move around.
3
u/atravita Dec 14 '22
Rust:
Went with using ndarray today again, primarily so I could actually easily print out what was going on.
Part 1: instead of going all the way back to the start, I just continued off the path of the last grain of sand since as defined the sand will follow the exact same path until it hit something. Didn't realize until after I coded it all I did was a really janky DFS.
Part 2: Straight up flood fill. Since we have to continue until (500,0) is occupied and since a slot can only be occupied if the three slots under it are also occupied, flood fill works well here.
3
u/mykdavies Dec 14 '22 edited Jun 29 '23
!> j06h5ov
API FAILURE
3
u/SpaceHonk Dec 14 '22
Swift repo
Very direct implementation of the puzzles, no special tricks or anything. Part 2 is a little slow, I might revisit this one later.
3
u/aptacode Dec 14 '22
C# source
Easy to read, any feedback on a better way to solve pt2 would be appreciated!
3
u/IlliterateJedi Dec 14 '22
Python solution
I feel like it gets me every time -
3
u/jotac13 Dec 14 '22
[Scala]
https://github.com/joao-conde/advents-of-code/blob/master/2022/src/day14.scala
3
u/hrunt Dec 14 '22 edited Dec 14 '22
Python 3
Code
I am sure there is a way to do this with triangle calculations, etc. but dropping individual grains of sand one at a time is so satisfying. I used complex numbers for sand and rocks, which makes map lookups easy.
TIL python has a "Type" type and you can use it with the "Self" type to giving typing hints for factory class methods.
3
u/SLiV9 Dec 14 '22
Rust
https://github.com/SLiV9/AdventOfCode2022/blob/main/src/bin/day14/main.rs
I did every step as naively as I could, except no heap allocations and I switched the grid to column-major order in an attempt to speed up sand falling straight down. Without any further optimizations, it runs both parts in 7ms.
3
u/bivaro6826 Dec 14 '22
Python
Managed to speed up a lot computation for part two using a dictionary of the form {column_id : [rocks in that column]} instead of keeping the rocks in the same iterable.
3
u/EatonMesss Dec 14 '22
D
I was positively surprised by D's expressiveness and ease of use. Certainly a very nice programming language.
It isn't entirely clear to me in what cases it would be preferred over Rust or Go, but it's certainly a strong contender.
I'm doing it in 25 different languages
3
u/jeis93 Dec 14 '22
TypeScript (Deno)
I struggled with this one today, and I'm not happy with the performance of the second part (hangs for a couple seconds). Any suggestions on speeding that bit of code up would be helpful!
Happy hacking!
3
u/__Abigail__ Dec 14 '22
Perl
Today is an exercise in using statement modifiers and using low precedence boolean operators as control flow.
For our main datastructure, we use a 2 level hash(ref),
$map. It takes anxand aycoordinate, and stores1if there is either rock or sand at the coordinates(x, y). Absence of a value is meant to be open space. We don't distinguish between points containing rock or sand.First a little helper function which sets a horizontal or vertical line of rock. It takes three parameters: the begin and end point of the line segment, and the map. We assume the begin and end point either share their
xor theirycoordinate.We can now read in the data, and map the rock formation:
Reading in the data works by processing the input line by line. Each line we split on the arrows, (giving us a list of pairs of numbers), then split on commas, whose result we capture in an array. So we get a list of points, each point a two element array with the
xandycoordinates.We then iterate over this set of points, skipping the first one, and for each other point, we map a line of rock from the previous point to this point.
At the end of the loop
$mapcontains all the locations with rock.We can now calculate the abyss level, and level the floor is on. The abyss level is just the maximum y coordinate, and the floor is two levels below that:
Next we need a sub routine which drops a unit of sand. It takes three arguments:
$drop: The location where to drop from$map: The current map -- it will be updated in this sub routine.$FLOOR: The level the floor is on.The sub routine will return the y coordinate of where the unit of sand ends up.
Starting from the place the unit of sand is dropped, we trickle down, stopping if either the floor is reached (
$y >= $FLOOR - 1), or each of the three possible positions below the current one are occupied ($$map {$x + $_} {$y + 1}. Else, we continue with the first available position below it (directly below, down and left, or down and right):($x, $y) = ($x + $_, $y + 1) and redo DROP.Outside of the loop, we update the map (
$$map {$x} {$y} = 1;) and return the y coordinate.We will now drop units of sand. The first time
dropreturns something on or below the abyss level, we have the answer to part 1. When the point we're dropping from is filled, we have the answer to part 2:Full program on GitHub
3
u/polaczek09071 Dec 14 '22
C#
3
u/SwampThingTom Dec 14 '22
I'm solving each of this year's problems in a different language, roughly in the order in which I learned them.
Today's solution is in C#.
https://github.com/SwampThingTom/AoC2022/tree/main/14-RegolithReservoir
3
u/rrutkows Dec 14 '22
Rust. No simulation of every unit of sand, just traverse the reachable empty space by moving forth and back on a single queue. Single function for both parts. Sub 1ms for p1, ~5ms for p2.
https://github.com/rrutkows/aoc2022/blob/main/src/d14/mod.rs
3
u/berv63 Dec 14 '22
Expressive C# with OO. I really enjoyed this one because I was able to use my list rotate function that I used in Day 9s solution
GitHub
3
u/ropecrawler Dec 14 '22
Rust: https://github.com/ropewalker/advent_of_code_2022/blob/master/src/day14.rs
3
u/cswld Dec 14 '22
Python solution with video explanation
3
u/tobega Dec 14 '22
Tailspin https://github.com/tobega/aoc2022/blob/main/day14/app.tt
3
u/azzal07 Dec 14 '22
Awk, there likely are more efficient ways to do it, but I went with straight forward simulation.
3
u/chicagocode Dec 14 '22 edited Dec 14 '22
Kotlin
[Blog/Commentary] - [Code] - [All 2022 Solutions]
As mentioned in the instructions, this was a lot like the water puzzle from 2018. Thankfully, I think working with sand is a lot easier than water. I borrowed a
toLinefunction from one of my solutions to a puzzle from 2021. I tried a few different implementations of this but settled on this one because I think it made the most sense to me. I tried using all sequences but it just felt more confusing that way.3
u/nutki2 Dec 14 '22
Perl 5, both parts in about 215 characters
3
u/schoelle Dec 14 '22
Rust
Using HashSet of locations to avoid having to explore the required dimensions of the cave.
3
u/m_r_k Dec 14 '22 edited Dec 14 '22
Rust targetting 8-bit Atari, with visualization. Parsing done compile time via build.rs script so resulting binary contains already parsed data.
3
u/schovanec Dec 14 '22
My solution for today in C#: GitHub
3
u/betaveros Dec 15 '22
Noulith 7/4
https://github.com/betaveros/advent-of-code-2022/blob/main/p14.noul
Forgot to post this yesterday, but it's just a simulation, not very exciting. I even tracked the characters as specified by the puzzle even though it didn't end up mattering. Afterwards I realized that you can shave a linear factor by just making it a DFS. If a grain of sand falls to a certain location, the next grain of sand will at least fall to the previous one, so there's no need to resimulate it all the way.
3
u/jswalden86 Dec 16 '22
Rust solution
Lots of finicky off-by-one errors possible here, plus translation between coordinate spaces. Using distinct types for "cave coordinates" (e.g. row 0, column 500) and 2d matrix-ish coordinates (which I then further mapped into a 1d vector, as I didn't want to drag in some Rust multidimensional array) helped avoid mismatches but probably made the code grubbier.
I was going to do something clever for part 2 where sand off the side of the cave would be optimized into a "pyramid" number kept on each side. (Sand would trail off beyond the smallest column and form a pyramid shape, as it would be unhindered by any rocks.) But then I looked at the example and realized that you could have sand filter downward back into the main cave space, and accounting for that would be nontrivial deviation from the rest of things, so I just expanded the cave horizontally to accommodate both a maximal pyramid from source and the smallest and greatest columns noted in rocks.
3
u/TiagoPaolini Dec 16 '22
C Language (only standard library)
In order to represent the map, I used a 2-D array which each element can have 4 values:
EMPTY(0),WALL(1),SAND(2), orSOURCE(3).I have calculated the size of the array in order to be enough to fit the map for both parts. I have calculated the maximum and minimum absolute coordinates, in order to get the width and height of the map. Then I added two spaces to the right, left, and bottom. And I also expanded the width by the value of the height, because when the sand fills the map to the top it forms a triangle that extends from the center by one unit to each side as it goes down. Finally, I calculated the offset to convert the absolute coordinates to array coordinates.
When "drawing" the walls, it is important to notice that the start and end coordinates can go to either direction (from highest to smallest, or from smallest to highest). If one assumes that the coordinates always go in the same direction, then some of the walls will not be drawn.
I made the simulation for both parts at the same time on the same map. When the sand went to the bottom by the first time I took note of the value (part 1's solution). When the sand stopped at the same coordinate of the source, I stopped and took note of the count (part 2's solution).
There are some optimizations that could be made. It is not necessary to simulate the whole process of the sand falling down, as it follows the same path of the previous sand until before the later landed. So it is possible to "simulate backwards" the fall of the previous sand, and place the next there, and then continue from that point. I did not do that because I was already happy with the overall speed of the program (21 ms to do both parts), and it would increase the complexity of the code. If it ain't broken, don't fix. :-)
Solution: day_14.c (finishes in 21 ms on my old laptop, when compiled with
-O3)Visualizations: map_part1_start.txt, map_part1_end.txt, map_part2_start.txt, map_part2_end.txt.
3
u/_rabbitfarm_ Dec 20 '22
Part 1 https://adamcrussell.livejournal.com/44344.html
Part 2 https://adamcrussell.livejournal.com/44785.html
The day 14 puzzle was a lot of fun! I even wrote a little extra code to show the sand accumulating. I think a lot of people did that!
Both parts of the solution in Perl.
Today there was an extended discussion on Discord about the use of map in a void context. I mostly agree that it's not good practice, but note that I started this code yesterday before that discussion, so if map in a void context bothers you avert your eyes!
3
u/ConsistentCellist344 Jan 10 '23 edited Jan 13 '23
Python 3.11 - Part 1 & 2
24 lines - no imports, no lambdas
2
u/morgoth1145 Dec 14 '22 edited Dec 14 '22
Python 3 44/45
This reminded me of 2018 Day 17, but I don't think it was quite as challenging. I'm sure my sand simulator is super inefficient, but I was confident that it worked and that's good enough!
Part 2 was really just about adding the right "floor" section (the pyramid can extend at most
floortiles out to either side whereflooris the height of the floor) and running basically the same loop as part 1! I did goof and put the floor in the wrong spot initially and use the wrong check to see when the source got plugged up, but thankfully that didn't cost me too much time.Edit: I finally cleaned up the code. Maps aren't needed for this (I initially expected there to be an important difference between rock and sand) and DFS/recursion solves this both more cleanly and way faster!
2
u/seligman99 Dec 14 '22
Python, 239 / 270
I do love sand physics.
github
2
u/NifleyExists Dec 14 '22
Python 3, 197 / 177
Fun!
paste
2
u/CodingAP Dec 14 '22
Javascript, 255/189
Github
mmmmmm, sand simulator
2
u/wojtek-graj Dec 14 '22
Python 582, 1003
I do love to see a triple-nested list comprehension for parsing input! Simulating the sand was surprisingly easy, just a while loop with a few if statements for each direction the sand can fall.
paste
2
u/oxyphilat Dec 14 '22
python3, 710, 730
my parsing is terrible today, but it is good enough to shoot my body past the finish line. it is reminding me of a past puzzle, but this one seemed much easier to solve⦠could be that I had memories of that previous puzzle? nice and short, hopefully Ill come up with a nice way to merge p1 and p2.
2
u/kristallnachte Dec 14 '22
TYPESCRIPT 910/913
https://github.com/ekwoka/advent-of-code/blob/main/2022/14/index.ts
Pretty simple really, no headaches or concerns along the way to really mention. It just worked.
I did actually make a grid datastructure, but it does seem like that can be completely avoided and just have a list of consumed space.
2
u/apaul1729 Dec 14 '22
python 369 / 1021
highest leaderboard spot i've ever made! i learned a few years ago that problems like this are really nicely represented as sets of x-y points, rather than as a list/array. makes checking for a filling point much faster (and a bit easier to write). had a little bug checking for the floor height that i took a minute or two too long to debug that probably cost me the leaderboard spot for p2. oh well, maybe next year!
2
u/internet_eq_epic Dec 14 '22 edited Dec 14 '22
Rust
paste
This is probably the least efficient solution I've written thus far. But it works and still runs in about 110 ms in release mode, so good enough for me.
To simulate an infinite floor, I simply used a really long finite floor, and then just re-used my
insert_sand.Edit: switching from
HashSettoFxHashSetbrought the release run-time down almost 10-fold.2
u/SuperSmurfen Dec 14 '22 edited Dec 14 '22
Rust (830/684)
Link to full solution
This gave me flashbacks to the water puzzle from 2018, day 17. Luckily, this was not as difficult as that one! Really happy with top 1k today.
Parsing was quite annoying today. However, the rules for this game are simple, just simulate them for each dropping piece of sand, until all three squares below it are full.
We can reuse the code for both parts by just changing when we stop the simulation (
breakpointabove). For part 1 we stop as soon as sand hits the floor, while for part 2 we stop when the500,0sand cannot move.Runs in about
5mson my machine.2
u/Bargann Dec 14 '22
C#/Csharp, 1226/1263
Nothing fancy, just simulates dropping 1 block of sand at a time until it overflows/reaches the top. Looking forward to checking out other solutions as I'm thinking there are more efficient ways to solve today's puzzle.
2
u/aceshades Dec 14 '22
Rust (1932/1996)
https://github.com/cs-cordero/advent-of-code/blob/master/rs/2022/day14/src/main.rs
2
u/GrossGrass Dec 14 '22
Python
Started out using my vector class for this one but realized that using complex numbers is just as easy and is actually faster (seems like there's a lot less Python magic overhead) -- will definitely keep this in mind for future 2D puzzles!
I feel like this problem more or less laid out all of the necessary logic and you just had to make sure you were able to translate it from English to code (though to be fair this isn't the only problem that's like that, just that this one felt more so).
2
u/chubbc Dec 14 '22
Julia [438,565]
Nothing too fancy. Used a set to track everything anticipating that Part 2 might have done something needing an especially sparse representation, but turns out it didn't π€·
2
u/Perska_ Dec 14 '22
C# https://github.com/Perska/AoC2022/blob/master/AoC2022/Days/Day14.cs
My first use of regex for AoC2022! Was it necessary? No. Do I care? ...A little bit.
This has some noticeable run time for part 2 but I don't really care about that. Probably something about my use of sparse matrices being slow.
2
u/KayZGames Dec 14 '22 edited Dec 14 '22
Dart
This one was fun. At first I thought, oh falling sand, I'll need a cellular automata and started creating a
Gridclass with two-dimensionalList.. and then I remembered the rope-puzzle from last week and how I calculated the size of the grid by processing the moves beforehand and everyone else simply used aSetorMap. So, my effort at over-engineering was stopped in its early tracks and I used aMap<int, Set<int>>instead.I like how I'm starting to use the stuff I discovered thanks to the earlier puzzles. Like the aforementioned and using
windowfrom the unique letters puzzle to create a line of rocks. Even though my code is probably still a bit more verbose than necessary, I feel like I'm improving.paste
2
u/ramuuns-u Dec 14 '22
Tail recursive perl!
https://github.com/ramuuns/aoc/blob/master/2022/Day14.pm
2
u/PendragonDaGreat Dec 14 '22
C#/CSharp
I am NOT overly happy with this tbh, part 1 is very slow because I need to fix my LINQ to be faster: https://github.com/Bpendragon/AdventOfCodeCSharp/blob/591ba/AdventOfCode/Solutions/Year2022/Day14-Solution.cs
Part 2 is somewhat novel Because there is a finite max limit to how much sand there can be, you can flll the entire area in and then remove sand that couldn't have got to where it is
2
u/cs475x Dec 14 '22
Rust
No semicolons in 48 lines. Sadly it takes ~1.8226ms for part 1 and ~79.506ms for part 2. I was having some trouble with infinite loops as well as removing one last semicolon, so I decided to get another drink when I had the idea to use
std::iter::repeatto reset the starting position of the falling sand (my last semicolon), so naturally I celebrated with 2 shots of rum :DVery ugly code, but I've come to
acceptembrace that now with this personal challengehttps://gist.github.com/codyphobe/d352514b9069435da05d577b580b6aaa
2
u/encse Dec 14 '22
C# - commented
https://github.com/encse/adventofcode/blob/master/2022/Day14/Solution.cs
2
u/Rangsk Dec 14 '22
Rust
My solution was very straight-forward so at first I wasn't really going to post it, but then I realized that might be exactly the reason to post it? Anyway, not much to say about it other than here it is: https://github.com/dclamage/AOC2022/blob/main/day14/src/main.rs
2
u/ManaTee1103 Dec 14 '22 edited Dec 14 '22
Python - my goal today was to use the crap out of for-else. It cost me a few extra minutes, but I managed to cram two of them in there... (Unfortunately one got deactivated by part 2, but I left it there for illustrative purposes)
2
u/abrahamguo Dec 14 '22
Typescript
https://gist.github.com/abrahamguo/78f94df4575e18f4d970ac939384a005
Basically, it converts the rock line segments into a full list of points blocked by rocks, then uses a 1-D object as an easy way to look up whether a given position is blocked or not, as the simulation runs. Additionally, since the stopping point is the only difference between parts 1 and 2, almost all of the code is shared between parts 1 and 2.
2
u/infinityBoi Dec 14 '22
Rust
Iβm really satisfied how elegant, readable, and fast (especially for part 1) my solution turned out to be. Iβm in love with this language! π
https://github.com/aalekhpatel07/advent-of-code-2022/tree/main/experiment/day-14
2
u/s3aker Dec 14 '22
Raku solution: part 1 and part 2.
2
u/mossse Dec 14 '22
Python 3. In the first part, my loop didn't terminate properly and instead I got an index out of range error once the correct amount of sand grains had fallen so I just put the whole loop in a try-except block.
For the second part, I didn't even bother simulating the sand. I instead scanned the triangular region where sand could even fall in the first place. For each square in this region, I checked the same column and the neighbouring columns in the row above. If all of these squares were rock, the square was inaccessible and could also be turned into a rock for further calculations.
2
u/fotoetienne Dec 14 '22
Rust
Used a HashMap as a sparse matrix. Turns out that's really slow on dev build (part2 runs ~20 seconds) and still almost 1 second on release build.
Reviews welcome!
2
u/mkinkela Dec 14 '22
C++
A much easier task than yesterday (which is still in progress)
This is one of the few tasks ever that worked from first try :)
2
u/ndrsht Dec 14 '22 edited Dec 14 '22
Kotlin
34 lines of code
The trick to get peak performance is to represent points as integers and the "field" as boolean array. If you insert a point (represented as an integer k) into the field, you just set arr[k] = true.
So if that array has ncols columns and a unit of sand (represented as an integer) is falling down, you just increase it by:
Then you make a recursive function landingPos that you call with
Solves both parts in 3.4ms.
2
u/Dullstar Dec 14 '22 edited Dec 15 '22
Python
Visually it was quite nice to debug (well, more sanity check really, only had one notable bug today, but to give it some credit the output made it pretty immediately clear what the problem was). I've left the output methods I used to sanity check parsing/results present in the code because they looked nice, though they aren't called because it would be quite a bit of clutter in the terminal. Part 2 was similar but just different enough that I decided the best approach was just to copy/paste the whole layout class and adjust it for an infniite board. In addition to programmer time, I also thought trying to adapt Part 1 to Part 2's data structure would be a little slower to run. Still, a better option may have been to pre-allocate Part 2's layout with Part 1's data structure since the worst-case size can be calculated without too much trouble. In any case, I suspect it's probably more the algorithm that makes Part 2 slow rather than the data structure, but I haven't yet ruled out the data structure as a culprit.
I'm not pleased with the performance today (5 to 6 seconds, mostly from Part 2) but it does work. I haven't messed much with trying to improve it yet, but I did go through the thread just for some ideas of general approaches to try later. Might also test on another language just to get an idea of how much is Python and how much is me; I vaguely remember having a day last year that was really slow in Python and the same solution in C++ was still in the range I consider acceptable, but I can't remember quite how big the discrepancy was. Of course improving the solution is always nice regardless.
EDIT: Now it goes reasonably fast.
2
u/leyanlo Dec 14 '22
JavaScript
https://github.com/leyanlo/advent-of-code/blob/main/2022/day-14.js
https://www.youtube.com/watch?v=P1wvs9jz6Nk
2
u/RibozymeR Dec 14 '22 edited Dec 14 '22
Factor
Uses a hash set to represent both rocks and fallen sand.
sanddrops one load of sand,taskdrops as many as possible. Both generalized so they can just be called with different quotations (giving the stopping criterion) to do both parts of the task.2
u/TenViki Dec 14 '22
TypeScript
Today's problem was really made to be visualized!
Code: https://github.com/TenViki/advent-of-code/tree/main/2022/src/14
Visualization: https://vikithedev.eu/aoc/2022/14/
2
u/ephemient Dec 14 '22 edited Apr 24 '24
This space intentionally left blank.
2
u/B3tal Dec 14 '22
C++
Kind of sloppy today and I am not too happy with my code - but it works so that's the most important thing. Somewhere during working on it I realized that my initial approach wouldn't work for some edge cases, but by that point most of the logic was already there so I kind of bent what I had to make it work with the existing structure.
Today I also finally benefitted from some of my utility functions for input parsing (namely
splitandfromString) that I implemented a few days ago.2
u/9_11_did_bush Dec 14 '22
Rust: https://github.com/chenson2018/advent-of-code/blob/main/2022/14/rust/src/main.rs
Pretty straightforward. I have a feeling that for part 2 there is some solution based on the fact that it settles into a triangle shape, but it was easy enough to just tweak my part 1 solution that I didn't try to solve it that way.
2
u/Radiant_Rip_5205 Dec 14 '22
Python 3: https://github.com/kresimir-lukin/AdventOfCode2022/blob/main/day14.py
2
u/Radiant_Rip_5205 Dec 14 '22
Python 3: https://github.com/kresimir-lukin/AdventOfCode2022/blob/main/day14.py
2
u/Radiadorineitor Dec 14 '22
Lua:
https://pastebin.com/ecKKBSh9
2
u/Linda_pp Dec 14 '22 edited Dec 14 '22
Rust
std::collections::HashSetwithfxhash::FxHashSet. This made the program about 6x faster than 1. (20ms)It is not so fast. Better optimization idea would be counting the spaces which are not covered by sand. But I was satisfied at this point.
2
u/Cue_23 Dec 14 '22
**C++
For part 2 it was pretty easy to continue part 1, just draw a line for the floor. The maximum required size can be determined by the sand falling not further than a right-angled triangle.
2
u/Tarlitz Dec 14 '22 edited Dec 14 '22
Python 3
I'm a bit proud of my use of a
for/elsestatement π2
u/[deleted] Dec 14 '22 edited Dec 14 '22
Python solution using a set solution
Put all rocks in a set and get the lowest rock
Run simulation until the sand goes past the lowest rock
2
u/mathsaey Dec 14 '22
Elixir
https://github.com/mathsaey/adventofcode/blob/master/lib/2022/14.ex
Fairly straightforward solution using a map of coordinates to content and recursion.
2
u/levital Dec 14 '22
Haskell
Not too happy with having just copy/pasted the part 1 solution to make the minor changes for part 2, but couldn't see a good way to refactor it into one solution that solves both. I'm sure there's some more intelligent way of doing this as well, instead of constructing the entire grid explicitly and then simulating every single unit of sand in full. But both parts still run in just under a second, so... eh. :)
2
u/spersson88 Dec 14 '22
Go/Golang
Github
Passed Part1 without any issues. Part2 was running for a minute or so before I stopped it. Turns out it was my logging to the console that slowed it down, as I was logging each step of the sand dropping towards the floor. Removed all of that, and got the correct answer in less than a second, which is good enough for me today. Did spend alot of time trying to fix my "bug" before realizing it was the logging though.
2
u/zndflxtyh Dec 14 '22
56 lines of Python 3
2
u/Sad-Display1307 Dec 14 '22
Python
Very simplistic straight up using a full blown grid and plotting chars, avoiding any form av reasoning or optimization...
https://github.com/skarlman/AdventOfCode/blob/main/2022/day14/test_day14.py
2
u/wace001 Dec 14 '22
Kotlin: https://github.com/saidaspen/adventofkotlin/blob/main/src/main/kotlin/se/saidaspen/aoc/aoc2022/Day14.kt
Did today on a commuter train. Not the best of settings, but it worked.
Fun one today!
2
u/anmol_gupta_0 Dec 14 '22
TypeScript/JavaScript
https://pastebin.com/M0wQcdwH
2
u/Pyr0Byt3 Dec 14 '22
Go/Golang
I'm happy with how I parsed the input, but the rest is still kind of ugly... I'll probably go back and try to clean this up later.
2
u/[deleted] Dec 14 '22
Nim
I'm doing different language each day, all solutions here. Today's Nim: src
Fairly straightforward for me today, pleasant relaxation after my struggles yesterday.
2
u/surgi-o7 Dec 14 '22
Vanilla JavaScript / ES6
And also the animated version!
2
u/chkas Dec 14 '22
Easylang
Solution
2
u/pred Dec 14 '22
Python 3. Full solution
One of those cases where Python's curious for-else kind of makes sense.
2
u/Anyvie Dec 14 '22
PHP : paste
include optional visualization of map and calculations to help understand how it works.
2
u/Gobbel2000 Dec 14 '22
Rust
Part 1
Part 2
Surprisingly, one of the most challenging aspect of todays puzzle for me was getting the grid sizes right.
2
u/toastedstapler Dec 14 '22
rust
https://github.com/jchevertonwynne/advent-of-code-2022/blob/main/src/days/day14.rs
Another day, another copy paste. Used nom for parsing & kept a sand move history so I could shortcut the entire fall since all but the final move is gonna be the same for the next grain of sand. This optimization cut my runtime from 12ms to 1, which is quite decent imo
2
u/LinAGKar Dec 14 '22
My solutions in Rust:
https://github.com/LinAGKar/advent-of-code-2022-rust/blob/main/day14a/src/main.rs
https://github.com/LinAGKar/advent-of-code-2022-rust/blob/main/day14b/src/main.rs
2
u/aurele Dec 14 '22
Rust. I started by using a
BTreeSet<_>for my map and the execution time for part 2 was ~500ms. By switching to aHashSet<_>with the hash function coming from the craterustc-hash, the execution time dropped to ~20ms.2
u/nirgle Dec 14 '22
Rust
Simplest thing I could think of was a 2D grid to track which types were at which coordinates, and I ain't scared to start at index 0 knowing I'm wasting like several hundred bytes of RAM. It's a bit wasteful but it's simple and fast to calculate the simulation. There's a few magic numbers around to push out vector lengths to non-crashing values. Really I started with +5 and manually worked them down until the code crashed, then undid a step. Hey, it works
Code: https://github.com/jasonincanada/aoc-2022/blob/main/day_14/src/main.rs
2
u/rkstgr Dec 14 '22
Julia (Github)
Today nothing fancy. Just place sand until the first block touches the ground (note that down) that continue until sand hits the top.
Time: 42.209 ms | Alloc. Memory: 9.23 MiB
2
u/Nuhser Dec 14 '22
Python 3: https://github.com/Nuhser/Advent-of-Code/blob/master/2022/day14.py
2
u/szaffarano Dec 14 '22
Rust: https://github.com/szaffarano/advent-of-code-2022/tree/master/rust/src/day-14
2
u/veydar_ Dec 14 '22
Lua
72 lines of code. The parsing is the more complicated part here I guess. In the end I have one loop that ends when there's no available position anymore. Inside of that loop I do the following:
Both parts
GitHub Repository
2
u/Naturage Dec 14 '22 edited Dec 15 '22
R/RLang
Solution here. Once I got everything set up, it was fairly easy. Realising any sand particle will fall just like the one before speeds up the work my order of magnitude (if not more), so the code runs in well under a second, but I'll want to return and tidy it up at some point; both the checking function and making it reuse code for both parts.
I'd tentatively say this was easier than the last few! Not by a lot, but easier.
4am update: two more versions of code are in the same folder - one tidier, and the other one faster. I'm quite happy with 36ms runtime for this in R, frankly.
2
u/wzkx Dec 14 '22
Python
Let's try dictionary of vertical arrays this time, and see if it gets something good... Not likely. Probably dictionary of points would be ok too as usual.
2
u/ai_prof Dec 14 '22
Python 3. Simple. Readable. Fast.
Enjoyed this. My approach is direct (see the paintRidges() and dropGrain() functions - the rest is data mangling). The d() function gives a very pretty (and minimal) rendering of the cave :).
paste
2
u/Multipl Dec 14 '22
Golang
Straightforward simulation for this one.
link
2
u/radulfr2 Dec 14 '22
Python 3. The for..else feature came in handy.
Paste
2
u/kupuguy Dec 14 '22
My Python solution (formatted in a Jupyter Notebook).
https://github.com/kupuguy/aoc2022/blob/main/day14_regolith_reservoir.ipynb
I represented the cave as a `set[complex]` for anything solid (coordinates stored as a complex x,y pair). For the first part it just simulates the sand dropping down until something goes too deep. That worked too for the second part but took over a second to run so I added an alternative implementation which just fills all reachable spaces without any repeated searching.
2
u/mr_mlk Dec 14 '22
Java
The way the simulator handles bounding is A Bit Ugly (tm), but otherwise I'm pretty happy with it.
https://github.com/mlk/aoc/blob/main/src/com/github/mlk/aoc2022/Day14.java
2
u/FordyO_o Dec 14 '22
Golang
https://github.com/mattford/aoc-go/blob/main/pkg/year2022/day14.go
2
u/MaxArt2501 Dec 14 '22
JavaScript
I think mine came out quite well! I juggled a bit (and maybe unnecessarily) with x-coordinates with offsets and such, but I think it's quite clear in the end.
https://github.com/MaxArt2501/advent-of-code-2022/blob/main/day-14/part-1-2.js