r/adventofcode • u/daggerdragon • Dec 11 '23
SOLUTION MEGATHREAD -❄️- 2023 Day 11 Solutions -❄️-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
Outstanding moderator challenges:
Community fun event 2023: ALLEZ CUISINE!
- Submissions megathread is now unlocked!
- 10 DAYS remaining until the submissions deadline on December 22 at 23:59 EST!
AoC Community Fun 2023: ALLEZ CUISINE!
Today's secret ingredient is… *whips off cloth covering and gestures grandly*
Upping the Ante Again
Chefs should always strive to improve themselves. Keep innovating, keep trying new things, and show us how far you've come!
- If you thought Day 1's secret ingredient was fun with only two variables, this time around you get one!
- Don’t use any hard-coded numbers at all. Need a number? I hope you remember your trigonometric identities...
- Esolang of your choice
- Impress VIPs with fancy buzzwords like quines, polyglots, reticulating splines, multi-threaded concurrency, etc.
ALLEZ CUISINE!
Request from the mods: When you include a dish entry alongside your solution, please label it with [Allez Cuisine!] so we can find it easily!
--- Day 11: Cosmic Expansion ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:09:18, megathread unlocked!
27
Upvotes
11
u/Smylers Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Vim keystrokes]
Another visual one!† Load your input, type in the following, and watch the galaxies get marked off and the total increase:
@a, which duplicates any rows containing no galaxies.@b, loop round turning columns into rows, to transpose the grid.@aagain, to duplicate rows that were originally columns.@bagain, to put the rows and columns back. (I suspect this step is unnecessary and the maths would've worked out the same with a transposed grid, but it was easier to check against the example with it the right way round.)|to mark it as processed, and remember its position withmm.@c, which loops round each remaining#, replaces it with-, and updates the total with the vertical and horizontal difference from the galaxy found in the previous step.@d, which turns all the-s back into#s, goes to the first one, then invokes@cto measure from that galaxy, then loops itself with@dto process from each galaxy in turn.Update: Removed the only number from my solution, to comply with [Allez Cuisine!]. It was a zero, to initialize the totalizer. But it turned out not to be needed:
Dhappily deletes nothing,⟨Ctrl+R⟩-, happily re-inserts that nothing, and the first distance calculation of the form+2-1+abs(8-4)works just fine without a leading zero; instead of the first+adding the previous total and the new distance it simply act as a no-op unary plus on the first number.I'm claiming my solution already contained exactly one ‘variable’, because
mmis used to store the cursor position in the'mmark, and a named mark is pretty much the same thing as a variable. (Whereas keyboard macros are more like subroutines, containing re-usable sets of instructions.)Just a shame I couldn't think of an esoteric language to program this in ...
† I solved yesterday's quite late. It also animates as it solves, so if you like this kind of thing and haven't seen it, do take a look.
4
u/Fyvaproldje Dec 11 '23
[LANGUAGE: Raku] [Allez Cuisine!]
https://github.com/DarthGandalf/advent-of-code/blob/master/2023/DayEleven.rakumod
Here's a sample of a digitless calculation of the distance the stars travelled.
4
u/Efficient_Beyond5000 Dec 11 '23 edited Dec 11 '23
[Language: Scratch]
https://scratch.mit.edu/projects/938348263/
Press R to reset, right click on the list to import the test or the input.
Click on the green flag to start computation and see a visualization of the galaxies.
[edit: remember to use turbo warp, to enable shift+green flag]
3
u/flwyd Dec 11 '23 edited Dec 11 '23
[Language: Julia] (on GitHub)
The Allez Cuisine challenge "Don't use any hard-coded numbers at all" when the problem statement involves the number one million :-/
Amusingly, I started playing around to see how to insert rows and columns in a 2D array in Julia, but couldn't find an elegant way to do it, so went for manhattan distance plus the range between end points intersecting with a list of empty rows and empty columns. Part 2 wasn't quite changing one number, but almost as easy.
There are probably ways to make this terser, but I'm tired and I think this is nicely readable.
3
u/arthurno1 Dec 11 '23 edited Dec 11 '23
[LANGUAGE: EmacsLisp]
The code was too long, so to please an angry bot here is the link:
https://github.com/amno1/AOC2023/blob/main/11.el
No expansion needed, it is just to calculate coefficient, which was relatively easy in itself.
3
u/[deleted] Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Forth] [Allez Cuisine!]
Who needs numbers and variables when you have a stack and ✨words✨? Forth's core library gives you all you could ever need for numbers:
true(-1),false(0),1+, and1-. Calculating the multiplier for part 2 was a piece of cake after defining some helper words:false 9+ 10* 9+ 10* 9+ 10* 9+ 10* 9+ 10* 9+ empty-multiplier !For non-constant values that need to be remembered throughout the program, I kept a pointer to some dictionary cells on the bottom of the stack. Then, some helper words returned addresses indexed from that pointer:
Cuisine code here edit: Refactored to remove all instances of digits in the code.
Regular, optimized code here. Got it down to solving both parts in around 5ms.
2
u/naclmolecule Dec 11 '23
[LANGUAGE: Python]
I'm sure people smarter than me have already figured out that the axes are independent:
2
u/optimistic-thylacine Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Rust] 🦀
Just a matter of getting the taxicab distance between pairs of points and using a prefix sum array to calculate their row and column distances.
The code below uses a custom 0-based BIT/Fenwick tree. The code linked uses simple prefix sum arrays instead, but was too large to post in the thread.
If you want to play around with the Fenwick tree, you can get it here.
Full solution
2
u/kevinwangg Dec 11 '23 edited Dec 12 '23
[LANGUAGE: PYTHON] [ALLEZ CUISINE!]
leaderboard: 14 / 2
Got second on the leaderboard today! That's by far my best placement so far, and almost certainly will be my best ever.
I kind of had a prophetic vision while starting part 1 and foresaw what the twist in part 2 was going to be. So I just made sure that my part 1 solution worked for part 2 as well, which meant that it took me only 20 seconds after submitting part 1 to submit part 2. It was very exciting, I figured that I was on track to get a good leaderboard position, and I was nearly shaking with adrenaline when I viewed my placement.
I guess I'm skilled at Manhattan distance problems, because my previous best placement (2022, day 15) also involved the metric.
2
u/damnian Dec 11 '23
[LANGUAGE: C#] [Allez Cuisine!]
GitHub
Today's secret ingredient is a single function that takes lambdas for getting/setting a coordinate and calculates everything in a single pass.
2
u/Eagle_1010 Dec 11 '23
[LANGUAGE: Python] for part1 replace the
1000000 - 1with12
u/DarthLasciel Dec 11 '23
[Language: Python]
https://github.com/DarthSpot/aoc2023/blob/main/tasks/task11.py
I know it's not much, but i'm really proud of coming up with a good solution for part 1, that i have a delta of 47 seconds between answering part 1 and 2. Also i used this years AoC to learn python :D
2
u/onrustigescheikundig Dec 12 '23 edited Dec 12 '23
[LANGUAGE: OCaml]
github
For once I correctly predicted the twist for Part 2, and wrote my algorithm for Part 1 to account for a different space expansion factor. The input is processed into a list of coordinates corresponding to galaxies as well as the coordinates of rows and columns that do not contain any galaxies (the "void" axes). The main algorithm then iterates over each axis along each dimension and adds the expansion factor (minus one) to any coordinates of galaxies that are greater than the coordinate of the axis. The galaxies are actually represented as a
coord Seq.t(that is, a lazy sequence structure) and the coordinate modifications are performed using aSeq.mapoperation, so I am not generating a new list for each encountered axis. Although this avoids the generation of new lists for each axis, there still end up beingn_axiscomparisons per galaxy, which is overall quadratic runtime in the worst case. In practice, there are far fewer void axes than galaxies in the problem input, and anyway the pairwise Manhattan distance calculations at the end are also quadratic.Also, I see a lot of comments talking about off-by-one errors, so here is some math explaining why you need to subtract 1. The formula for (say) the final xfin coordinate of a galaxy with one void column to its left can be redefined as a sum of distances from some arbitrary origin:
where
(su)= screen units and(vu)= void units. Our expansion factor isf (su / vu).This simplifies to (dropping "_void_edge" for brevity and grouping like terms):
We know that the width of a void column is 1 screen unit, so
Converting void units to screen units, we get
2
u/jbrownkramer Dec 12 '23
[LANGUAGE: Python]
I have a solution that is linear in the size of the grid.
First observation is that you can collapse along the y axis get the x contribution and vice versa.
The one dimensional case: consider the number of paths crossing from index i to index i + 1. It is the number of galaxies at index <= i times the number at index > i. Add these products all up to get the total length (multiplying by the expansion factor for indices with 0 galaxies).
2
u/The6thProgrammer Dec 12 '23
[Language: C++]
Code: https://github.com/rlempka/advent-of-code-2023/tree/main/day-11
Part 1: Spent time constructing the "expanded" universe manually and then used the Manhattan distance between each pair of points to find the shortest paths
Part 2: Realized my part 1 was only partly optimal, instead of expanding the universe, I simply calculated Manhattan distance and added the number of empty rows between each pair of points multiplied by 999999 to the Manhattan distance, along with the number of empty columns between each pair of points multiplied by 999999.
That is, each distance calculation looked like this in code (multiplier = 1000000):
long long dist = (manhattanDistance(galaxyPoints[i], galaxyPoints[j]) + (countRowsBetween(emptyRowIndexes, galaxyPoints[i], galaxyPoints[j]) * (multiplier - 1)) + (countColsBetween(emptyColIndexes, galaxyPoints[i], galaxyPoints[j]) * (multiplier - 1)));2
u/ianMihura Dec 17 '23 edited Dec 21 '23
[LANGUAGE: go]
Tried brute force for part 2, but no luck. Had to do some refactoring. IMHO the final solution for part 2 ended up being simpler than part 1!
https://github.com/ianmihura/advent23/blob/master/day_11/day_11.go
19
u/4HbQ Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Python]
Do you ever start mindlessly refactoring, only to end up with code that you can no longer explain?
3
u/weeble_wobble_wobble Dec 11 '23
[LANGUAGE: Python]
GitHub (31 lines each, with a focus on readability)
Part 1 expands graphically by inserting rows and columns, part 2 calculates the galaxies' adjusted coordinates
13
u/4HbQ Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Python] Code (6 lines)
Instead of solving the problem for (x,y)-coordinates, my
dist(ps)function solves for one direction only. Simply computedist(xs)anddist(ys)separately, and add the results:13
u/kaa-the-wise Dec 11 '23 edited Dec 12 '23
[Language: J]
Well, Python one-liners are simply not short enough, so today I am trying J!
+/,(+/\*(1e6 1{~*)*(-~+/\.))(+/"1,.+/)'#'=];._2(1!:1<'11.in')Same solution written in Uiua, as a bonus:
/+♭××⊃⊃\+(⊏:1e6_1±)(-:⇌\+⇌.)⍉⊟⊃/+≡/+⊜(=@#)≠@\n. &fras "11.in"Translation of /u/4HbQ's python solution.
22
u/seligman99 Dec 11 '23
[LANGUAGE: Python] 70 / 23
github
That super rare event happened: My solution for part 1 perfectly set me up for part 2! I never thought I'd see the day!
10
u/WhiteSparrow Dec 11 '23
[LANGUAGE: Uiua]
Very easy once I understood the task... This solves part 2, for part 1 just change the Scale param.
8
u/voidhawk42 Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Dyalog APL]
8
u/timvisee Dec 11 '23
[Language: Rust]
Day 1 to 11 still under 1 millisecond in total! 🚀
7
u/vu47 Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Kotlin, functional programming]
I'm actually a software engineer in astronomy, so this felt like Monday morning coming early to me.
Thankfully, I predicted (for once) what part 2 might be, and could see that the data was a sparse representation, so it made sense to calculate the empty rows and the empty columns, determine the original coordinates of the galaxies, and then determine their adjusted coordinates by the parameter of how much an empty row or column was worth.
After that, it was easy to just produce all pairs, calculate the difference using the Manhattan metric, and then sum them up to get the answer.
This was one of the more fun problems for me so far, with the exception that my test case for problem 1 kept failing. D'oh. After about half an hour of having no idea what was going wrong, I realized that I carelessly copy-pasted the example input that was already adjusted for the empty rows and columns, so I was getting a number bigger than expected. After I fixed that, the test case passed, and everything was smooth sailing.
Very happy with my solution to this one.
paste
7
u/leftfish123 Dec 11 '23
[Language: Python]
OK, this most likely is an inefficient solution. I store the galaxies as a list of [x, y], apply offset to their coordinates one by one depending on how many lines/columns with smaller indexes there are, then use itertools.combinations to find pairs and finally calculate Manhattan distances between the pairs. That's a lot of overhead that includes over 100 000 pairs in the combinations iterator, though it works pretty quickly.
But...I managed to think about it early in the day during my commute to work, then after the entire day I sat down, wrote it and had both parts done almost at the same time. As a complete amateur, I am darn proud of my decision to calculate instead of manipulating the 2D array.
7
u/Gprinziv Dec 13 '23
[LANGUAGE: Python 3] This one was nice and easy!
I did part one by actually expanding the array by one at each point and solving, but then I saw part 2 and realized that there was no way I was going to to the math on arrays that big, so instead I kept a list of all the "thresholds" where the graph was empty and if a star crossed those lines, you simply added the required number of extra steps (1 for part 1, 999999 for part 2).
I think itertools saved me a hell of a lot of time here writing up a combinations() function myself. I'm still a bit flu-y and there are probably better ways to do multiple steps of this in one pass, but this was a good one.
5
u/DFreiberg Dec 11 '23
[LANGUAGE: Mathematica] Mathematica, 97/289
Actually made it on the leaderboard; it was by one single second, but it counts. Had to completely redo my Part 1 solution upon getting to part 2, but that's par for the course; I have nobody but myself to blame for not seeing "Do what you did before, but do it a million times!" coming.
Setup:
Part 1:
Part 2:
5
u/YenyaKas Dec 11 '23
[LANGUAGE: Perl] 1193/562
Today's task was quite Perl-friendly. I extracted the galaxy coordinates as array of
[ $x, $y ]pairs usingpos()on rows, and then computed which coordinates where occupied usingThen I walked X and Y separately, counting the unoccupied rows twice:
Part 2 was only about using
1_000_000instead of2.Full code for Part 2 here.
All my AoC solutions in Perl
5
u/bucketz76 Dec 11 '23
[Language: Python]
I overthought the hell out of this problem. I originally manually expanded the graph, then ran BFS from every galaxy. Then, for part 2, I changed it to instead encode the row/col expansion as edge weights and then use Dijkstra's algorithm (which worked, but was super slow). Finally, my brain turned on and I realized you can just take the manhattan distance and add in the penalty for each empty row/col in between. Ugh.
paste
5
u/Good_Brain_2087 Dec 11 '23
[LANGUAGE: Javascript]
Part 1 with variable spacing, just change the spacing for part 2
Solution: https://github.com/sanishchirayath1/advent-of-code/blob/master/2023/day11/index.js
5
u/kbielefe Dec 11 '23
[LANGUAGE: Scala] GitHub
Relatively straightforward. I was fortunate enough to not have done the actual expansion in part 1, just made a note of the empty rows and columns. Only hitch was 1000000 times is actually 999999 'extra' spaces, so my first answer was too high.
5
u/pkusensei Dec 11 '23
[Language: Rust]
Not the best solution as it is not fast at all. It also reveals something interesting: in debug mode (
cargo test)HashSetis noticeably slower thanBTreeSet, but in release mode (cargo test --release) it runs as well, if not slightly better. Code5
u/chubbc Dec 11 '23
[LANGUAGE: Uiua]
Pad link
5
u/[deleted] Dec 11 '23
[Language: Rust]
Easy-peasy compared to day 10. I've done enough of these by now to know that the challenges will usually bite you in the butt with big numbers, so I represented each galaxy as a pair of indices and modified them accordingly. Only thing that bit me was an off-by-one error in Part 2, which I quickly fixed.
Part 1
Part 2
4
u/MarcusTL12 Dec 11 '23
[LANGUAGE: Julia] 385/187 Code
Took me a bit too long to realize that I could just do the manhattan distance + the number of empty columns + rows, and then part 2 was essentially trivial as I just multiply the extra distance by 1000_000 - 1. That -1 lost me a minute...
4
u/jonathan_paulson Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Python 3] 315/239. Solution. Video.
Lots of bugs today :( In part 1:
In part 2:
4
u/eisemsi2 Dec 11 '23
[Language: C++]
Part 1 : Quite ease. Just added another row/col whenever I found an empty row/col. Then calculated the grid distance b/w all pairs.
Part 2 : I added a different row/col (containing all '!') and considered it to be sort of "space warp". Then after I calculated prefix arrays to access how many such row/col "space warps" are between any 2 points in the grid (space). Then all remains is to use a similar formula used in part 1 to calculate distance.
Link : https://github.com/eisemsi2/Advent-of-Code-2023/tree/master/day11
4
u/sanraith Dec 11 '23
[LANGUAGE: Scala]
Code is available on my github: Day11.scala
I only keep track of the galaxy points of the map and expand everything "backwards", so that I don't have to shift the coordinates of the negative space:
4
u/Hungry_Mix_4263 Dec 11 '23
[LANGUAGE: Haskell]
https://github.com/alexjercan/aoc-2023/blob/master/src/Day11.hs
Solved using Manhattan distance, and when the path intersects with one of the empty rows, you add
factor - 1to the cost.4
u/sgxxx Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Python]
10 lines solution for both parts by expanding the coordinates instead. https://github.com/sayan01/advent-of-code-2023/blob/master/11/p.py
TIL about shortcut to transpose matrix using zip(*lines)
4
u/busseroverflow Dec 11 '23
[LANGUAGE: Go]
The code is on Github.
Part 1: 0.18ms, Part 2: 0.18ms
Like many others, I saw part 2's twist coming so I made sure my solution would scale with any expansion factor.
First, I read the input and stored the galaxies as a list of coordinates, each with a row and column integer value.
Next, I needed to identify the rows and columns to expand. I iterated over all galaxies to identify which rows and columns had galaxies. I then computed the minimum and maximum of those values, giving me the range I needed to work with. Within this range, I determined which columns and rows didn't have a galaxy; these are the ones that expand.
To apply expansion, I needed to adjust the coordinates of each galaxy. I decided that expansion would push galaxies to the right and downward only. I shifted each galaxy to the right by the number of empty columns that were to its left. Same thing vertically: each galaxy shifts down by the number of empty columns above it.
Once I had the new coordinates, I computed the distance between each galaxy pair. Since there are no obstacles between galaxies, we can compute the Manhattan distance, which is easy to implement and runs blazingly fast.
With part 1 solved, I needed to adapt my code for part 2. This involved only a small change: instead of adding 1 for each empty row/column, I added 999,999. This involved adding a `factor` variable to my `expand` function, so a 3-line change in total.
The code runs really fast (well under a millisecond). The part that takes the longest to run is computing all the distances between galaxies, because it's O(n²), where n is the number of galaxies. The part that expands the space between galaxies is only O(n).
4
u/MarcoDelmastro Dec 11 '23
[LANGUAGE: Python]
https://github.com/marcodelmastro/AdventOfCode2023/blob/main/Day11.ipynb
(
np.insert()directly on original map for Part 1, computing new coordinates for Part 2)4
u/NickKusters Dec 11 '23 edited Dec 11 '23
[LANGUAGE: C#]
Fun day again! I immediately realised I should NOT actually expand the space and just track how much we need to add.
I wrote these helpers to check how many times we need to pad, calculate the bounding box out of two points to do that check and to calculate the Manhattan Distance between two points.
Basic approach: Map the input to just galaxy coordinates, Find empty cols & rows for the expansion, generate permutations for the Galaxies (wrote that code as an extension a long time ago), calculate bounding box, padding, manhattan distance, and add them all up together.
For part 2, I just needed to introduce a modifier to the padding logic, taking into account that, as part of the map, you already count the space once, so you need to multiply by modifier -1.
Part 1:
Part 2, you just change the padding:
Parsing Input:
Helpers:
video
4
u/philippe_cholet Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Rust]
My rusty-aoc repo & today' solution here.
Part 2 was obvious from the start, right? That it would expand much more.
Solved in 27mn.
Sadly, this is slowest solver so far: benchmarked to 3.68ms each part ^^. Probably inevitable since there a lot of pairs. Maybe use "bitvec" crate instead of a vector of booleans. I don't want to add a dependency for now. But if the grid was less than 128x128, I would have done with u128 integers.
I did the off-by-one error of 1_000_000 instead of 999_999.
4
u/bulletmark Dec 11 '23
[Language: Python]
4
u/[deleted] Dec 11 '23 edited Dec 30 '23
[LANGUAGE: Google Sheets]
https://github.com/zdhmd/advent-of-code-gs/blob/main/2023/day11.md
The problem is easy but creating a one formula solution is extremely difficult due to the limitations of the software. I was eventually able to get a one-formula solution for both parts but it's extremely slow. (Takes ~10 minutes to load)
4
u/cbh66 Dec 11 '23
[LANGUAGE: Pickcode]
Of course, my original part 1 solution actually inserted new empty rows and columns to the grid. Hit a couple of off-by-one errors as I refactored to handle any expansion rate, but it was nice that I could test it with my input and an expansion factor of 2 and double check I got the same answer for part 1.
https://app.pickcode.io/project/clq0uo6hhag4yop01pznl6jew
4
u/Synedh Dec 11 '23 edited Dec 11 '23
[Language: Python]
Python shenanigans.
Expansion handeling on these galaxies
4
u/nilgoun Dec 11 '23
[Language: Rust]
Well... today was not my brightest.. -_-
At least the final solution is clean..
Code
4
u/Althar93 Dec 11 '23 edited Dec 11 '23
[LANGUAGE: haskell]
Old me would have naively expanded the image and cried when reaching part 2.
Wise(r) me simply extracted the (x,y) coordinates of galaxies and offset their respective x/y components by the number of (empty) rows/columns above/left of their position.
Part 2 was as simple as multiplying offset by 999999.
My solution for part 1 & 2
[EDIT: I need to revisit my pair generation function to only generate unique pairs, in my haste/lazyness I just halved the result][EDIT 2: I've addressed the doubling of pairs in my implementation ; unsurprisingly, the execution cost is halved from 38ms to 19ms on my system for both parts]
4
u/Lysander7 Dec 11 '23
[LANGUAGE: rust]
github
Nice, now I have some time to go back and solve part 2 of yesterday's puzzle :^)
4
u/whiplashoo21 Dec 11 '23
[LANGUAGE: Python]
So proud to only need to change one variable for Part 2 to work. github
4
u/malobebote Dec 11 '23 edited Dec 11 '23
[Language: Typescript]
I wouldn't have figured it out if I hadn't eventually gotten the hint that you consider 1_000_000 as a factor of 999_999. Sheesh.
https://pastebin.com/ZthpCbxT
4
u/lucamanzi Dec 11 '23
[LANGUAGE: Haskell]
code
Simple Solution, I felt I had to implement a smart way to store the Universe
It paid off: part2 was trivial
4
u/tridactyla Dec 11 '23
[LANGUAGE: Lua]
I did most of the work with pencil and paper to find a nice small formula for the solution.
Given the number of galaxies
n, expansion scalek, sortedxcoordinatesx1throughxn, sortedycoordinatesy1throughyn, the solution can be calculated with a single sum:Here's my code:
4
u/loquian Dec 12 '23
[LANGUAGE: C++]
github, 12.384 ms (both parts together)
A normal day's work--expanding the universe, finding the distance between every pair of galaxies. You know. The usual stuff.
4
u/i_have_no_biscuits Dec 12 '23
[Language: Python]
Fairly happy with this linear-time solution -
Code is here Average time taken is ~1ms including parsing.
4
u/CutOnBumInBandHere9 Dec 12 '23
[Language: Python3]
Some people say I have a
numpyproblem. I disagreeLink
4
u/joshbduncan Dec 13 '23
[LANGUAGE: Python]
Not blazing by any means but pretty straightforward.
1
u/dag625 Dec 11 '23
[LANGUAGE: C++] 815/442
Code: AdventOfCode/2023/day11.cpp at master · dag625/AdventOfCode (github.com)
Yesterday I managed to just get into the top 1000, and today I was solidly in. That's a trend I don't expect to continue.
A lot of things just clicked for me. Another grid problem to use my grid utility code on. I realized that by requiring Manhattan distances, I could just add the number of empty rows and columns to the total to calculate the expanded distance. And then when part 2 was just changing the expansion rate I just needed to change my `++dist` to `dist += expansion_factor`. So, this was probably close to the best-case scenario for leaderboard positioning for me.
1
u/m1el Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Python]
Took me too long to find a few copy-paste errors, 746/291
1
u/yfilipov Dec 11 '23 edited Dec 11 '23
[Language: C#]
https://pastebin.com/hZRzH12T
1
u/AlexAegis Dec 11 '23
[Language: TypeScript]
Part 2 surprised me, because even part 1 is super slow unless done properly. Since I had a fancy graph+path finding implementation at hand I tried with that but it was super slow. Only when I printed the paths it found I realized I could just use the manhattan distances, see how many empty rows/columns it passes through and add them together.
If we interpret the input like this:
then:
part1
part2
1
u/vanveenfromardis Dec 11 '23
[LANGUAGE: C#]
GitHub
There's not too much to say about this one, personally I didn't find it too interesting.
1
u/oupsman Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Golang]
Not much to say here, but that was kinda fun today
https://raw.githubusercontent.com/Oupsman/AOC2023/main/d11/advent_11.go
1
u/globalreset Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Ruby] 6825 / 6309
Got a late start on this one, but it was pretty easy. In part 1, I did the expansion of the data array and then just did manhattan distance. But realized I needed something smarter for part 2. So I just created a Set for each empty row and another one for each empty column, then and'ed that with the Set of cols and rows between my galaxies.
github
1
u/shouchen Dec 11 '23 edited Dec 11 '23
[LANGUAGE: C++] https://github.com/shouchen/AdventOfCode/blob/master/aoc2023/Day11/Day11.cpp
No need to even store the whole grid. Just parse the input into:
(1) A list of galaxy locations.
(2) An array of bools for which rows have galaxies in them.
(3) An array of bools for which columns have galaxies in them.
Then, go through all combinations pairs of galaxies in (1) and sum up the distances.
To find the distance between two galaxies in the above, the actual path taken doesn't matter as it will still cross the same number of intermediate rows and columns. Just walk across those rows and add 1 if that row contains galaxies (2) or 2 if it doesn't. Then do the same thing walking through columns using (3).
For part two, just change 2 to 1000000.
1
u/TankLivsMatr Dec 11 '23 edited Dec 12 '23
[Language: Go]
Hey look, a day that didn't completely stress me out. (Looking at you Day 10).
This was relatively simple. For part 1, for expanding, we can just use Go's handy dandy
append()algorithm to add in the extra line where necessary.From there I just created a hashmap where the key was the galaxy number, and the value is the galaxy coordinates. When calculating the distances, I just looped through all of the keys and calculated the distances.
Calculating the distances is as simple as Manhattan Distance.
Part 1
For Part 2, instead of adding another row or column of "." I instead added another row or column of "*". Which signifies a certain amount to "jump" by. Rather than adding x amount of rows and lines.
That way, when constructing my hashmap, if it finds a row or a column with "*" then it increases the "Actual Row/Column" and then uses that when storing the hashmap.
Part 2
(Edit: formatting) (Edit 2: removing profanity)
1
u/ell5e Dec 11 '23 edited Dec 13 '23
[Language: Dart]
2 line diff between part 1 and part 2 :)
https://github.com/ellemouton/aoc_2023/blob/main/eleven/main.dart
1
u/The_Doctor_33 Dec 11 '23
[LANGUAGE: Kotlin]
I just debugged part 2 for ~2h because i used Integer instead of long.
https://github.com/Stenz123/advent-of-code_2023/blob/main/src/main/kotlin/days/day11/Day11.kt
1
u/d9d6ka Dec 11 '23 edited Dec 12 '23
[Language: Python]
Commit
The shortest path is a Manhattan one :) the trick I used is to check whether any empty row or column is between the corresponding coordinates of two galaxies and to add extra values to the distance in non-expanded universe.
UPD: if-statements in the function of
exdistcan be removed, the're from the solution for Part 1 :)1
u/NigraOvis Dec 11 '23
[python 3]
my awful, but fast python solution
1
u/LeoLion32 Dec 11 '23 edited Dec 11 '23
[LANGUAGE: PYTHON]
https://github.com/leolion3/advent-of-code-2023/blob/main/11-cosmic-expansion/solution.py
Ended up rebuilding the 'image' in part 1, then realised it would be easier to just work with coordinates. Itertools for combination generation.
1
u/RobertGauld Dec 11 '23 edited Dec 12 '23
[Language: Rust]
I bashed out a solution this morning but was a bit disppointed that it took about half a second (edit, it was actually 200ms). This afternoon some inspiration for an alternative solution hit, now runs in 2ms.
https://topaz.github.io/paste/#XQAAAQCDCQAAAAAAAAA6nMjJFMpQiatRknmsqDuZN+nT4l78dKkl0LLcYiOrVcxPgj+besnL5H9BuVtINBVOAQVjCFPtgZJAtzSWAdEAIxpc5Ci5kZFjws5QV/q/VEHj/iQ3DzHayfpa0RCX7zIzpmioUY0J5FehnAeFBfatcbXagy01wQqdQJE/NBMMEx0ZhDRDaOHebbGJSiZTKMWaGyWB1/xRnRRd1JwnWhQO+lcETDoiNWF+YqVfkXg9F6IqB3g+HpSZLjzLoXWKzTG71GxJ+FhXbqFEGeBlVHz6izUokrDkZliorAnOQrVfik/uNykpphMZbeYlgrZ5Pq4Vh91p1X3i6aYJJ7ykxSPhEiWAU1QQPqz+FlwUyc/FwhdYexUSau3eTbjO1han4HMhkK3MYa4j4Jv5uYoq1f/KyPMUalc1+LfI1xjOVpJjG7MgqOo3LLEsONsLomawnCR/TZN0GCT0fu2ZwLZBO3RWrSprMs5LPiiyXTV59Jm+XkbJEv8ZPHIVeBOORn3UmKVlx4/ywq5WR0OgizYTyZId9uSFuo8LgKsS2WDvFU6nlW7h8eGssimOuRflApfZeBgQSssZXnPvptbTU3Wxf7FCqLBCtT7FBh2uYPoQ+bCzZ5gyr07Y5m8nh2W2XKTWcjKMFFkER92lctuF+EdDPjTw837bgyrRx2lhGr+KOpMmC8TMJfohsZ3cVIeQsBjeNW2MgbGa+2RrNkFq86IWg1am0ymjJRX1dDragr8cP22JT1bC5I5Abv6qfFFswrrhfEsbxH+vka0uWZnu2OV5WsXvJJTsD8a1XgawlWONOMKlu/8yG4833RQCbC3Kcj9b8+z2ILryKabfgvEPZQqJypFzNc90dvrSdSNToxqwrDP7IMMiAib/F+sJgSEgDKVqLK4mwaNy4YHbj5jF0idtQTXEuYFgyRx6bGfGu1iILeH6hl1s8wPBD2lYx1RE4XjvBK171Z3SeoQfiPaP207WG6ka8Oseq8TBfhyeKimPvgU/Dmhki2pVUqVpFvG9dGkjQOAnrRwMbHbiqmwOyldx3kineNRcItFWGyCKDdmWRdhRw0Xc6AcBc34NcDoyeNZpnJSk08beb8LN9RefvYuaF9kE8EZStnQ27pq/d4iyqsECQVt16fcEbw7NUm8ebmZ/Maykz/ykrCQ8y3dj9Pqd8oYUZmZwGiM8bPPf1yVdp1Vu2fAwLzsjDc++Ikow89ReuSRj0d88BGD/4+A6Tw==
1
u/Jolly_River Dec 11 '23
[LANGUAGE: TypeScript]
https://github.com/DarioTheLuca/my_advent_of_code/blob/master/aoc2023/src/day11/index.ts
3
u/DeadlyRedCube Dec 11 '23
[LANGUAGE: C++20/23] (305/165)
D11.h on GitHub
Maybe the best rank I've ever gotten? And part 2 would have been lower if I hadn't off-by-oned on part 2 and lost a minute (1 + 100000 != 1000000)
First part I almost went and modified the grid but then I realized I could just keep a count of empty rows as I scanned through (And offset stored galaxy Y coordinates by the count of empty rows found).
Then it took a minute before I realized it also said "empty rows and columns" and I had to add a little "Scan from right to left for empty columns and update the galaxy coordinates accordingly" loop
Then for part 2, I just had to change the increment to a += 999999 (Except I did it as += 1000000 first, whoops), so I kinda lucked into a great part 2 setup!
3
u/r_so9 Dec 11 '23 edited Dec 11 '23
[LANGUAGE: F#] 1552/971
Much easier after the Day 10 part 2 slowdown.
Interesting block - a generic way to find gaps in a list, and the "expand" function (factor is the expansion factor, 2 for part 1 and 1,000,000 for part 2).
paste
3
u/EffectivePriority986 Dec 11 '23
[LANGUAGE: perl5]
[code] [embarrassing video]
I wasted waaay too much time on accidentally copying the pre-expanded example (oops!) and an extremely silly and shameful implementation of part 1. For part 2, I started over and the new implementation was actually shorter and simpler. After doing extremely badly on the race, I went back and optimized part 2 even more.
3
u/xelf Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Python] pretty python (~8lines)
Instead of expanding the universe, I just move the galaxies based on how many empty rows/cols there were before it.
Had a bit of a debug issue because I forgot the (-1) and the number weren't quite right.
3
u/Szeweq Dec 11 '23
[LANGUAGE: Rust]
My code modifies the points before calculating distances. This makes a significant difference in speed (about 2x) and memory allocation since we don't have to reiterate each empty columns and rows. No maps or sets involved.
Code: https://github.com/szeweq/aoc2023/blob/master/src/bin/11.rs
The hero of this code is
space_pointsfunction.3
u/stribor14 Dec 11 '23 edited Dec 11 '23
[LANGUAGE: C++]
Only thing I store are coordinates, so no dilation of huge matrices.
Link to code
edit: cleaning up the code
3
u/Greenimba Dec 11 '23
[LANGUAGE: C#]
First time an AoC solution has just worked right off the bat for 1 & 2, with only a minor mod to allow bigger space multipliers and no off-by-one errors 💪
C# code
3
u/ka-splam Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Dyalog APL]
Part 1, expands the map array, takes galaxy coordinates, sums the outer-product distance between all pairs, halves the total:
Yes I tried it on part2 hoping Dyalog's bit-packing would Just Magically Work(tm), but no expanding by millions runs out of memory. Instead of expanding the map, this calculates how many expanded-regions each coordinate crosses in X and Y directions and adds that onto their coordinates:
It's not nice how hard it was to debug, how repetitive yet different expanding x and expanding y are to cope with being . Or how much code it is overall, compared to u/voidhawk42 's here.
3
u/AnxiousMasterpiece23 Dec 11 '23
[Language: JavaScript]
A fun little search problem. I calculated distance gradients for each galaxy to every other galaxy. I'm happy I ignored the statements about physically adding rows and columns and went with a row and column cost on each node from the start. Part two became just adding a variable expansion factor.
https://github.com/ccozad/advent-of-code/blob/master/day-11.js
3
u/ClutchClimber Dec 11 '23 edited Dec 11 '23
[Language: GO]
Works for both p1 and p2
Github
3
u/4HbQ Dec 11 '23
[LANGUAGE: Python]
Here's my golfing attempt (197 bytes):
Basically just a compact version of my normal solution.
3
u/Cyclotheme Dec 11 '23
[LANGUAGE: QuickBASIC]
Github link
3
u/jvdsandt Dec 11 '23
[LANGUAGE: Smalltalk]
GitHub
3
u/No-Monk8319 Dec 11 '23
[LANGUAGE: Rust]
The solution parses the input into coordinates, then uses hash sets to track rows and columns that require expansion. This approach streamlines the expansion process, avoiding the need to manipulate the matrix directly. The calculation of distances between galaxy pairs is optimized by pre-computing the expanded distances, significantly reducing computation time, especially for the massive expansion factor in Part Two.
Runtime:
Part 1: ~100µs
Part 2: ~100µs
https://github.com/NikolaIliev/aoc_rust/blob/master/src/bin/year2023_day11.rs
3
u/gyorokpeter Dec 11 '23
[LANGUAGE: q]
3
u/[deleted] Dec 11 '23
[Language: Python]
Keep all the indexes of the expanded rows and columns but don't expand them. Just do a combinations of all stars positions and take the difference in positions, if any special row or column is between the two stars, add
n-1wherenis the number of expansions (2 for part 1 and 106 for part2).Code here.
3
u/[deleted] Dec 11 '23
[Language: Golang] [Code]
Used the right approach for part 1 to make part 2 really easy, but then I got bit hard by an off by one error since I was adding 1M columns and rows instead of 9999999. Aaargh. Runs in about 500 us on my Lenovo Yoga Slim 7.
3
u/weiss_i_net Dec 11 '23
[LANGUAGE: Python]
paste
The actual solution is straight forward, but I had some fun with trying to turn python into haskell afterwards and want to share :D
I turned one of my list comprehensions into a point-free chain of functions and left the other one normal:
3
u/DrunkHacker Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Python]
Pairwise manhattan distance calculation is easy and we just add in an expansion factor for any intervening cols/rows.
3
u/IronForce_ Dec 11 '23
[LANGUAGE: Python]
Took me forever to figure out that I didn't have to implement some crazy pathfinding algorithm and that I could've just Google'd/ChatGPT'd "how to calculate shortest distance between 2 points on a grid" to save me 4 hours of work. I ended up using the Manhatten distance formula to calculate the distance after failed attempt after failed attempt to get scipy and tcod to work (but at least I learnt how to use numpy to generate 2D arrays :D)
Second part required a bit of wrangling of my code to get it to work, after I naively tried to brute-force (again) generating 1 million rows/columns per empty row/column and crashing VS Code. I ended up
stealingtaking inspiration from another solution and used this function to generate an expanded coordinatePart 1 and Part 2
3
u/p88h Dec 11 '23 edited Dec 19 '23
[LANGUAGE: Mojo] vs [LANGUAGE: Python]
https://github.com/p88h/aoc2023/blob/main/day11.mojo
https://github.com/p88h/aoc2023/blob/main/day11.py
Linear scan to find expansions followed by a linear scan to compute all distances.
No combinatorics is necessary here since Manhattan distances are easily summable. For a brief explanation, let's take a star i at
\[Xi,Yi\]and compute all distances from that star, to all K stars such that for each j theirXj <= Xi and Yj < = Yi. Or, in space-faring terminology, 'up and to the left'. Each individual distance is then(Xi-Xj+Yi-Yj)for all j from 1 to K. But that can also be written asK\*(Xi+Yi)-SUM(Xj+Yj)over K; and it's reasonably easy to keep that sum up to date as you traverse through the hyperspace. The 'up and to the right' is left as an exercise for the reader (or you can attempt to decipher myobscure scribblestotally readable code linked above). With that, we get the time for each part to around 20 μs in Mojo, and a bit more for its Pythonic friends.3
u/Valefant Dec 11 '23
[LANGUAGE: Kotlin]
Initially I used an array to represent and modify the grid for part 1, but this was not feasible for part 2. I rewrote it to track the empty distance and then shifting the coordinates of each galaxy
https://gist.github.com/Valefant/8567597bd9fadf9637baf8785972cf00
3
u/dodo-obob Dec 11 '23 edited Dec 11 '23
[LANGUAGE: rust]
https://github.com/dlesbre/advent-of-code/blob/master/2023/11/puzzle.rs
I do love a puzzle where part 2 is trivial ! I store the galaxies as pairs of coordinates. Expansion is done by computing the set of missing columns/rows, then shifting all coordinates by the number of smaller elements of that set. For part 2, just add a multiplier to that shift (which isn't 1_000_000, it's 999_999, small fact that took WAY too long to debug)...
You could go bit faster by using a balanced ordered set to quickly get the number of missing rows/columns smaller than self in
O(log n)time instead ofO(n), but the solution is fast enough as is (sub millisecond time).3
u/Valletta6789 Dec 11 '23
[LANGUAGE: Python]
Mine solution for both parts. Found indices of empty rows and cols, and if a num coordinate is higher than one of the indices, then I update a coordinate by multiplyng num of previous indices by koef.
https://github.com/Aigul9/AdventOfCode/blob/master/year2023/Day_11/main.py
3
u/After-Leadership2183 Dec 11 '23
[LANGUAGE: Golang]
After a very difficult yesterday's puzzle (part 2), today is a breeze
https://github.com/macos-fuse-t/aoc/tree/main/2023/11
3
u/Diderikdm Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Python]
3
u/patrick_iv Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Kotlin]
3
u/SpaceHonk Dec 11 '23
[Language: Swift] (code)
I initially implemented Part 1 by adding rows and columns to a 2D array of (empty/galaxy) values, and that worked just fine for a growth of 2.
For part 2 I had to completely rewrite this to be based of an array of galaxy coordinates instead, so parts 1 and 2 just pass different "growth" parameters to the same function.
AFACIT there's no suitable "permutations" or "combinations" method in the stdlib so I had to write my own.
3
u/errop_ Dec 11 '23 edited Dec 11 '23
[Language: Python 3]
Not sure if I could make it shorter/more efficient, but I'm quite happy I was lucky enough to set up Part 1 in a way such that I didn't need any hard refactor for Part 2. There's actually no need to re-run the code for Part 1 with different "expansion factor", as the last line of my solution suggests.
Paste
3
u/Radiadorineitor Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Dyalog APL]
3
u/mist_mud Dec 11 '23
[LANGUAGE: Javascript]
Created a 'Galaxy' class to store galaxies, along with a couple of sets to store empty row/cols.
Ran through each galaxy, noting how far it would expand, then expanded the universe :)
Manhattan for distances.
Learnt a little bit about field declarations, static methods, and set creation from an Array in the process, which was nice :)
partOne gist
partTwo gist
3
u/odnoletkov Dec 11 '23 edited Dec 11 '23
[LANGUAGE: jq] github
3
u/azzal07 Dec 11 '23
[LANGUAGE: Awk] Using the most advanced vectorised absolute value function: put all the values in
$0andgsub(/-/, "").This calculates the pairwise distances without expansion (
A) and the distance from one expansion (B) in a single pass. The final result is thenA + B*twheretis the time (e.i. the number of expansions).3
u/sergiosgc Dec 11 '23
[LANGUAGE: Rust]
Code
Most of the work is done preparing the input. I read a set of coordinates, then pair each coordinate with (empty_cols_before, empty_rows_before). Then, it's just iterating over all combinations of galaxies and calculating the manhattan distance after expansion for each pair of galaxy coordinates.
For part 2, the only difference is the expansion multiplier. I managed to avoid the obvious off-by-one error trap.
3
u/Tipa16384 Dec 11 '23
[LANGUAGE: Python]
Avoided obvious trap :-)
paste
3
u/tcbrindle Dec 11 '23
[Language: C++]
A nice gentle one today!
While reading in the values, if there was no galaxy found in a particular row then I increment the running
yvalue by the expansion factor. At the same time, I record which columns had galaxies found in them. Once I've read in all the positions (with "expanded" y-coords) I go back and expand the x-coords for each galaxy as appropriate.After that, calculating the distances is simple, although it does remind me that I need to add a
combinationsfunction to my library...Github
3
u/silt_lover Dec 11 '23 edited Dec 11 '23
[LANGUAGE: rust]
Hard mode rust - #![no_std], no std collections. I allocated 3 slices today: empty rows, columns and galaxy coordinates. Then just an iteration over all pairs of coordinates, checking which empty rows/columns they have between them. Not depending on dynamic memory allocation made me avoid the trap today :^)
github
3
u/msschmitt Dec 11 '23
[Language: Python 3]
Solution with expansion factor, runs in 0.05s
My idea for part 1 was that instead of capturing the galaxies with x,y coordinates from the input, I (step 1) create two lists: one is indexed by x coordinates, other by y. Each lists's elements point to a list of the galaxies that have that x or y coordinate.
This way I could expand the universe by (step 2) just running through each list, and inserting a new empty element at where there's an element with an empty list. The nature of the list means that this automatically adjusts the x or y coordinates that follow that insertion point.
Only then do I run through each list, (step 3) building a new list of galaxies with their x,y coordinates. And then just Manhattan distance (thanks AoC!) to calculate the path length.
For part 2 inserting a million elements wasn't going to scale, but I realized that I didn't actually need to do that at all. I could jump from step 1 to 3, by having step 3 keep a running x or y value as it iterates through the x or y list, incrementing x or y by either 1 or the expansion factor.
3
u/scibuff Dec 11 '23 edited Dec 11 '23
[Language: JavaScript]
3
u/[deleted] Dec 11 '23
[LANGUAGE: Rust]
My Day 11 on GitHub
Luckily I didn't actually expand the galaxy in part 1, but simply counted empty rows/columns as 2 when working out the distance. This meant part 2 was as simple as adding a parameter to my two functions - nice!
3
u/Jessseee Dec 11 '23
[LANGUAGE: Python]
I am happy today's puzzle was a little easier again. I was overthinking the solution at first, but quickly came to this (in my opinion) quite simple solution.
Also on GitHub
3
u/SwampThingTom Dec 11 '23
[LANGUAGE: Rust]
Blessedly easy after yesterday.
Github
3
u/aexl Dec 11 '23
[LANGUAGE: Julia]
Fun little puzzle today! I think that I have never solved part 2 in such a short time after having solved part 1. I simply counted the empty rows and columns between two galaxies and "moved" one galaxy further apart when calculating the distance. For part 2 I simply had to multiply the number of empty rows and columns by (1000000 - 1), that's it.
Solution on GitHub: https://github.com/goggle/AdventOfCode2023.jl/blob/master/src/day11.jl
Repository: https://github.com/goggle/AdventOfCode2023.jl
3
u/bo-tato Dec 11 '23
[LANGUAGE: Common Lisp]
3
u/Gravitar64 Dec 11 '23
[LANGUAGE: Python]
Part 1 & 2, 26 sloc, runtime 47ms
Storing only the coordinates of galaxies, create a list of empty rows/cols by set-subtraction, expand by adding 1/999.999 to x- (insert col) or y- (insert row) coordinates in the reverse list of empty rows/cols. Sum the Manhattan Distances for every itertool.combinations-Pair.
3
u/remy_porter Dec 11 '23
[LANGUAGE: Python]
Pretty straightforward. I made it up to a few days ago without using NumPy, but now that the seal is broken, I can't be arsed to avoid it.
3
u/xHyroM Dec 11 '23
[LANGUAGE: Python]
part 1
part 2
I used Manhattan distance instead doing BFS (probably everyone did) - https://en.wikipedia.org/wiki/Taxicab_geometry
For part 2, i used bisect
3
u/jstanley0 Dec 11 '23
[Language: Ruby]
I stored the galaxy coordinates as a hash from X coordinate to array of Y coordinates, and I expanded space with the following function:
I then transposed the array and repeated for the other axis, i.e.
For part 2, all I had to do was add the factor argument. My initial answer was too high until I realized I needed to subtract 1 from the scale factor.
Full solution
3
u/mcnadel Dec 11 '23
[LANGUAGE: Python]
Today was a lot of fun! My solution involves two main components:
I tried to make my code very short while still keeping it somewhat readable. GitHub
3
u/mothibault Dec 11 '23 edited Dec 17 '23
[LANGUAGE: JavaScript]
If, like me, you built a code that doesn't scale well for part 2, that's the hack you're looking for. https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day11.js
(with tons of inline comments)
3
u/CCC_037 Dec 11 '23
[Language: Rockstar]
Let's start by building a spare universe, shall we?
And then, for part 2, let's build a bigger spare universe.
I would also like to note for the record that both solutions today successfully used a recursive function to add up the distances.
3
u/artesea Dec 11 '23
[LANGUAGE: JavaScript]
Part 1: Over complicated, does several twists on the map, adding in extra .... lines where needed. Then plots where each galaxy [x,y] is, loop through each against any further galaxies. Simple difference between the x and y cords gives the distance. Sum all together.
Part 2: Stopped redrawing the map, instead found the original x,y locations on the input, and also tracked any cols or rows which were full of .... Then when looping through the galaxies check if any of the paths cross an empty row or column and add the expansion value (minus one as it's already been counted).
3
u/wsgac Dec 11 '23
[LANGUAGE: Common Lisp]
Source
I wanted to go with 2D arrays for efficiency, but found it a bit hard to expand them, so I went with lists instead.
In Part 1 I recreate the literal expanded map, locate the galaxies and sum their distances in the NYC metric.
In Part 2 I'm more economical and just locate empty rows and columns, and then adjust galaxy coordinates according to the numbers of preceding row and column "empties".
3
u/vss2sn Dec 11 '23
[LANGUAGE: C++]
Part 1
Part 2
(Each file is a self-contained solution)
3
u/psr Dec 11 '23
[LANGUAGE: Python]
I was quite happy with mine, once I worked out why expansion wasn't working.
3
u/mrvoid15 Dec 11 '23
[LANGUAGE: Golang]
https://github.com/akashdeepnandi/advent-of-code/blob/main/day11/main.go
3
u/bamless Dec 11 '23
[LANGUAGE: J*]
Today was interesting.
I see pretty much everyone used Manhattan distance which is arguably the optimal solution. Unfortunately I wasn't familiar with it (but now I am wich is an awesome part of reading these posts after having done the problem) and to be honest I didn't give the puzzle much of a tought, so I went with the solution that seemed the most straightforward to me.
I basically used a modified version of Bresenham's algorithm that never does a diagonal step and rasterized a line between each pair. During line rasterization, I correct the number of steps by looking up a precomputed table of expansion factors instead of pre-expanding the input.
The runtime isn't exceptional (~0.5s on my machine) but much faster that I would've expected for this sort of algorithm on an interpreted language.
Part 1 & 2
3
u/rune_kg Dec 11 '23
[LANGUAGE: python]
https://github.com/runekaagaard/aoc-2023/blob/master/day11.py
Super happy with this one. Did the first ten days with Nim and nice to be back to python again :)
3
u/RookBe Dec 11 '23
[Language: Rust] [Language: all] Blogpost explaining my solution in Rust, the explanation can be used for all languages: https://nickymeuleman.netlify.app/garden/aoc2023-day11
3
u/SymmetryManagement Dec 11 '23 edited Dec 12 '23
[LANGUAGE: java]
https://github.com/linl33/adventofcode/blob/year2023/year2023/src/main/java/dev/linl33/adventofcode/year2023/Day11.java
solveVectorin the above file implements the solution outlined below.A vectorized solution with time complexity O(R*C) and O(R+C) extra space, where R is the number of rows in the grid and C is the number of columns in the grid.
Observations
Benchmark
0.023 ms for each part including IO and parsing.
Edit
Reading another solution made me realize I was very close to a much simpler and more efficient solution. I can just calculate every row/column the way the empty rows and columns are calculated - by counting the galaxies before and after (or on) each row/column. 🤦♀️
Now it takes 0.020 ms per part.
3
u/vbe-elvis Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Kotlin]
This morning Part 2 got to me with an off by 1 error, due to not taking the existing line into account. Figured out my mistake quickly in the evening. Here is my solution:
https://pastebin.com/MjCX2UyD
Creating the galaxy maps (repeat the forEach for xPos):
3
u/Ok-Group4131 Dec 11 '23
[LANGUAGE: Python]
part 1&2 - github
I did part one by manually expanding the grid, and then stored the indexes of the empty rows and columns for part 2. My part two solution is quite slow, so any ideas for optimising would be appreciated
3
u/Kfimenepah Dec 11 '23
[LANGUAGE: NodeJs with Typescript]
Day11
Today was one of those sweet days where I managed to solve part 1 in such a way that part 2 was no issue at all. It took me about a minute to finish part 2 and that was only because my initial expansion rate was set to 1M instead of 1M - 1
3
u/Outrageous72 Dec 11 '23
[LANGUAGE: C#] https://github.com/ryanheath/aoc2023/blob/master/Day11.cs
Not too difficult, I just knew the expansion would be bigger in part 2 :) The only gotcha was the wording "10 times bigger", but a simple minus 1 fixed that problem :D
3
u/rjray Dec 11 '23
[LANGUAGE: Clojure]
GitHub
Not my best code-- I (foolishly) implemented part 1 by actually expanding the matrix representation of the "image". When part 2 was unlocked, that obviously wouldn't have been viable. So what I wrote for part 2 is also what I should have written for part 1. I'll revisit the code later to clean it up and improve it.
3
u/0x2c8 Dec 11 '23
[Language: Python]
https://github.com/alexandru-dinu/advent-of-code/blob/main/2023/11/solve.py
I really like problems where the grid operations can be simplified using numpy.
Representing the grid as a binary numpy array allows for straightforward detection of empty rows and cols via
argwhere. The shortest distance b/w 2 points is then given by Manhattan distance plus checking how many empty rows & cols are b/w the 2 points.3
u/Secure_Pirate9838 Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Rust]
YouTube screencast: https://youtu.be/VOahESJS-vc GitHub: https://github.com/samoylenkodmitry/AdventOfCode_2023/blob/main/src/day11.rs
Today, part 2 was the same as part 1. Copilot was practically useless to teach me how to use PriorityQueue, thankfully Google is still there.
Update after I saw other's solutions: Manhattan...
3
u/Hunky524 Dec 11 '23
[Language: Rust] GitHub
Nothing crazy, my goal with these is to write code that is performant, and readable. Uses itertools to create the tuples, and rayon for parallel distance computation.
3
u/icub3d Dec 11 '23
[LANGUAGE: Rust]
Yay, manhattan distance (apparently also called taxicab geometry) :)
Solution: https://gist.github.com/icub3d/1057d162dbee5fe9f0fb96563b6a20fd
Analysis: https://youtu.be/N3Y5ZSzAvXU
3
u/biggy-smith Dec 11 '23
[LANGUAGE: C++]
Manhattan distance makes its first appearance this year! I knew there would be funny business in part 2, so in part 1 I stored and offseted individual points, then used the Manhattan distance to sum. Changing the expansion value worked for part 2, although I got caught out by setting expansion incorrectly the first time. Fun one.
https://github.com/biggysmith/advent_of_code_2023/blob/master/src/day11/day11.cpp
3
u/oxlade39 Dec 11 '23
[LANGUAGE: Rust]
Code
Had already written manhattan distance and point based coordinate utilities
3
u/Imaginary_Age_4072 Dec 11 '23
[Language: Common Lisp]
Day 11
My solution just figures out where the blank rows/columns are then adds any that are between a galaxy pair to the manhattan distance.
I got part 2 wrong for my first answer as I tried to add 1,000,000 lots of the blank lines, when it should have been adding 999,999 since there's already one lot included in the manhattan distance.
3
u/CainKellye Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Rust]
Such a relief after yesterday's (and today's) hell with day 10 part 2!
https://github.com/cainkellye/advent_of_code/blob/main/src/y2023/day11.rs
3
u/yieldtoben Dec 11 '23
[LANGUAGE: PHP]
PHP 8.3.0 paste
Execution time: 0.0486 seconds
Peak memory: 9.9729 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
3
u/aarnens Dec 11 '23 edited Dec 11 '23
[LANGUAGE: Rust]
Both parts run in ~560ms, which is really slow considering it's like 5x the other days put together, lolI know that it's because of my triple for loops, but as of right now I don't know how to get rid of them lol. Might update later.At least I didn't have to think a lot for part 2Got both parts to run in ~12ms, while still keeping the triple for loops. Not quite sure why it's so much faster (or rather, why the original was that much slower) but i'm not complaining lol.
improved code: https://pastebin.com/dJ9bE6bp
original paste: https://pastebin.com/UHt9jbjG
3
u/darkgiggs Dec 11 '23
[LANGUAGE: Rust]
Paste
I'm learning Rust this year. I had fun doing row expansion while parsing the input and column expansion in a single pass through the vector of galaxies.
I do both parts at the same time and it runs in roughly 5ms on my laptop.
3
u/xavdid Dec 12 '23
[LANGUAGE: Python]
Step-by-step explanation | full code
Very pleased with today! I got the list of grid points that held galaxies. Then I got all the empty lines by removing any
row/colfrom the respective set of all possible points. Then I iterated all points and increasedrowandcolby the number of empty rows that were smaller than that row/col, which stretched everything nicely. From there, it was taxicab distance.Part 2 was just turning part 1 into a function and adding a multiplier! The increased distances didn't slow me down at all since they were just bigger numbers. Simple and clean.
3
u/AJMansfield_ Dec 12 '23 edited Dec 12 '23
[LANGUAGE: Fortran]
A thoroughly vectorized solution that runs in 147 μs (274 μs including I/O).
https://github.com/AJMansfield/aoc/blob/master/2023-fortran/src/11/cosmos.f90
3
u/iskypitts Dec 13 '23
[LANGUAGE: Zig]
Part 1 (naive solution where I actually expanded the map) and Part 2
3
u/Robin_270 Dec 15 '23 edited Dec 15 '23
[LANGUAGE: Python]
Not so easy one, but I've managed to solve both parts. It's a combination of brute-force approach for the first part (where it didn't cause any problems) and a smart one for the second part. You can see it in the repo here.
4
u/Sourish17 Dec 11 '23
[LANGUAGE: Python3] 78/166
p1: https://github.com/SourishS17/aoc2023/blob/main/eleven-a.py
p2: https://github.com/SourishS17/aoc2023/blob/main/eleven-b.py
Finally got some more global points :D (totally not spending all my time on AoC when my Cambridge Uni admissions interview is tomorrow...)
My only note today is that you can transpose an array in Python by doing this (check my p1 code to see how I used it)
y=list(zip(*y))Happy Monday everyone :)
2
u/piman51277 Dec 11 '23
[LANGUAGE: JavaScript] 76/168
Link to GitHub
Today was fairly simple. Part 1 uses the naive solution while part 2 uses the optimal solution.
The key part was knowing shortest distance between points on an unrestricted grid is just taxicab distance.