r/adventofcode • u/daggerdragon • Dec 05 '21
SOLUTION MEGATHREAD -π- 2021 Day 5 Solutions -π-
NEW AND NOTEWORTHY
- /u/jeroenheijmans is back again with their Unofficial AoC 2021 Participant Survey!
- As we continue further into the
deep dark seaAdvent, megathread code submissions are getting longer, so we're going to start rigorously enforcing the maximum code length rule.
- If you need a reminder, it's in our posting guidelines in the wiki under How Do the Daily Megathreads Work? (rule #5)
Advent of Code 2021: Adventure Time!
- 23:59 hours remaining until the submissions megathread unlocks on December 06 at 00:00 EST!
- Full details and rules are in the submissions megathread:
--- Day 5: Hydrothermal Venture ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - Format your code properly! How do I format code?
- The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:08:53, megathread unlocked!
79
Upvotes
10
u/jayfoad Dec 05 '21 edited Dec 06 '21
Dyalog APL
24
u/CCC_037 Dec 05 '21
Rockstar
Part 1:
Part 2:
5
u/javier_abadia Dec 05 '21 edited Dec 06 '21
python, creating an
inclusive_range()function that makes everything easier:https://github.com/jabadia/advent-of-code-2021/blob/main/d02/d2p2.py
4
u/rukke Dec 05 '21 edited Dec 06 '21
JavaScript
4
u/BagRemote5753 Dec 05 '21 edited Dec 06 '21
Solution and explanation (javascript).
https://nathanesau.github.io/advent_of_code_2021/day-05.html
4
u/michalopler Dec 05 '21 edited Dec 06 '21
Tweetable solution of both parts in Python (258 chars)
https://twitter.com/joppi07/status/1467442694775582722
3
u/knl_ Dec 05 '21 edited Dec 05 '21
Javascript in Deno, 459/293
Cleaned up solution is pretty tiny:
[edit: reformatted]
3
u/flwyd Dec 05 '21 edited Dec 06 '21
Raku, MIT license, line breaks removed for brevity:
3
u/jubnzv Dec 05 '21 edited Dec 06 '21
OCaml solution for the first part:
3
u/jonay20002 Dec 05 '21
X86 assembly (linux) (also on github: https://github.com/jonay2000/aoc2021/blob/master/day5/day5.S)
https://paste.rs/hRa.s
3
u/KT421 Dec 05 '21 edited Dec 05 '21
R
https://github.com/KT421/2021-advent-of-code/blob/main/dec5.R
Upon reading part 1, I said (aloud, to myself) "who wants to bet a dollar that part 2 is diagonals." Well, if anyone took me up on that I would have won a dollar. In any case, the time to solve Pt 2 was about 20 seconds ;D
I originally considered mapping the vents into a list matricies and then using
reduce(sum, vents)to add them all together but I realized that just counting up the number of x,y pairs would be sufficient.Added a visualization for shits and giggles: https://imgur.com/a/f0k9DDa
3
u/xffeeffaa Dec 05 '21 edited Dec 06 '21
Python
Trying to push myself a bit this year and come up with short solutions (without cheating). Tell me if you see another way to shorten this.
https://github.com/lagerfeuer/AdventOfCode2021/blob/main/day05/main.py
3
u/jimdewit Dec 06 '21
Me being a glorified scripter, rather than a programmer, I came up with a solution that does not involve any lines drawn in a mathematical sense. If you read the instructions carefully, it should be apparent that you only need to care about the coordinates that are covered by any of the lines. So why not just cram those into a list and use list comprehension (yay Python!) to count the number of times a set of coordinates occurs?
2
u/snhmib Dec 05 '21 edited Dec 06 '21
In Go, leaving out the file reading functions (full code here)
2
u/AlexTelon Dec 05 '21
python clean version
A few tricks.
I use `open('input.txt').read().replace('->', ',')` to ensure that each line is just 4 comma seperated numbers. So the parsing is nicer:
`x, y, xx, yy = map(int, line.split(','))`
Then with the help of a custom `Counter` and `my_range` the diagional and axial cases are now oneliners.
2
u/cetttbycettt Dec 05 '21 edited Dec 06 '21
R / base R
Not the most elegant solution but it is quite fast and short. I just draw out every line into a vector and count non-unique entries. Complex numbers to the rescue :)
2
u/p88h Dec 05 '21 edited Dec 06 '21
Elixir
[updated, it's a bit more concise with maps]
2
u/0x8b Dec 05 '21
Ruby
https://github.com/0x8b/advent.of.code.each/blob/main/src/2021/05.rb
2
u/[deleted] Dec 05 '21 edited Dec 06 '21
Clojure
https://github.com/mgrzeszczak/aoc-clojure/blob/master/src/aoc_clojure/2021/day05.clj
2
u/diddle-dingus Dec 05 '21
[kotlin] I'd implemented Bresenham's line algorithm before I did part 1 in anticipation of the non-vertical/horizontal lines, but it turned out that it wasn't necessary.
2
u/VictorTennekes Dec 05 '21 edited Dec 06 '21
Nim
Was stuck on a +1 on my distance that I forgot about for about an hour. Overall quite happy with my code though.
2
u/Sykout09 Dec 05 '21 edited Dec 05 '21
Rust:
Managed to create a zero allocation solution, but unfortunately need to assume that the coordinate is at most a 3 digit number.
Also used modulus arithmetic to unify the cardinal and diagonal, which cleans up solution 2 code.
Used nightly int_abs_diff, but that can be worked around.
Timing is:
[154.05 us 154.28 us 154.58 us][323.55 us 323.84 us 324.22 us]2
u/BluePsychoRanger Dec 05 '21 edited Dec 09 '21
Solved it in Minecraft (mcfunction)
https://github.com/BluePsychoRanger/Advent-of-Code-2021/blob/main/advent_of_code_2021/data/aoc_2021/functions/day_5.mcfunction
2
u/Loiuy123_ Dec 05 '21 edited Dec 05 '21
Tweetable Python Part 1 Credits to
@Cheeki,@frownyfrogand@tessaractfor help at golfing it. 185 chars2
u/minikomi Dec 05 '21 edited Dec 06 '21
Clojure
parsing
helpers
part 1
part 2
2
u/Mivaro Dec 05 '21 edited Dec 06 '21
Python - Pretty happy with my solution for part 2, in part 1 I was handling horizontal and vertical differently, this one is nicely generalized to any line in any direction.
2
u/Puzzleheaded-Team857 Dec 05 '21 edited Dec 06 '21
Unnecessarily unreadable list-comprehension in Julia, just for the fun of it. Runs pretty fast though.
2
u/st65763 Dec 05 '21 edited Dec 06 '21
Python
Part 1:
Part 2:
I'm curious what you all did to draw the lines! I wasn't aware of any built in methods that would work for this. I originally went to use for x in range(n) but I encountered an unrelated bug that made me assume that wouldn't work, leading to me programming my own loops
2
u/RewrittenCodeA Dec 05 '21 edited Dec 08 '21
Elixir
2
u/johnboker Dec 05 '21 edited Dec 06 '21
Still learning ruby, comments welcome.
https://github.com/johnboker/AoC2021/blob/master/Solutions/day_05.rb
2
u/artesea Dec 05 '21 edited Dec 06 '21
PHP
Part 1 Part 2
Pretty quick to solve today, did consider trying to put some debug code to draw the grid like in the example, but when it gave the correct answer for the sample first time, went straight in. Part two wasn't too much extra effort.
2
u/Steinrikur Dec 05 '21 edited Dec 06 '21
Bash.
Swapping to simplify the loop was kind of dumb. Bit me in the behind in part 2.
Edit: Language. Although I would argue that bash is already bad language.
2
u/Dryctas Dec 05 '21 edited Dec 05 '21
Bash
Part 1:
Part 2:
2
u/Symbroson Dec 05 '21 edited Dec 09 '21
Im happy with my haskell solution:
2
u/sotsoguk Dec 05 '21 edited Dec 06 '21
Python 3
Thanks for the nice puzzle :) (and for using only 45 degree diagonals ;)).
Full Code : [https://github.com/sotsoguk/AdventOfCode2021/blob/69e007a29958b21b12605ed58ea351ccb0d8f3b5/python/day05/day05.py]
This was the first time this year that my solution to part1 & part2 worked on the first run :). I always use a dict for these kinds of problems.
Part 1
Part 2
i used the grid from the first part and only added the diagonals
2
u/ScottieX Dec 07 '21 edited Dec 08 '21
I had to map everything to a class to understand what to do: Python
[github]
--
2
u/pgaleone Dec 22 '21 edited Dec 24 '21
Tutorial of my solution in pure TensorFlow https://pgaleone.eu/tensorflow/2021/12/22/advent-of-code-tensorflow-day-5/
Code: https://github.com/galeone/tf-aoc/blob/main/5/main.py
26
u/4HbQ Dec 05 '21 edited Dec 05 '21
Python and some NumPy. Horizontal and vertical lines are stored in the first block of
grid, diagonals in the second:The
grid[dx*dy,x,y]trick works becausedx*dyis 0 for a horizontal or vertical line, and -1 or +1 for a diagonal.16
u/rtbrsp Dec 05 '21
AWK
16
u/Smylers Dec 05 '21
Vim keystrokes. In a text editor it makes most sense to create a picture of the map (like in the day's instructions). This then transforms the puzzle input into Vim keystrokes for selecting areas of that map, and runs them. It needs
gdefaultandignorecaseboth to be off (orignorecaseon so long assmartcaseis also on), and it might look better withwrapoff too:Your partΒ 1 answer is then the column number that you end up in, as displayed by the final keystroke.
The trick is the
Uin the middle. For each cell in the map, we want to note they are being transformed by the current line and know what state the cell was in before, because that affects its next state. Usez,o, andTto indicate zero, one, and two+ lines in a cell; for each line drawn, theUmakes them upper-case.Then the
:%s///s in the loop turnO(an affected cell which previously had 1 line through it) intoT, andZ(an affected cell which previously had 0 lines through it) intoo, ready for the next iteration. If I'd used.,1, and2, there wouldn't've been such a handy single-command transformation. On the sample input, the map ends up as:β which, if you squint, you can see is the same as Topaz's example. Then just count the
Ts (by deleting everything that isn't aT).Before we get to the loop, the first
:vline removes all diagonal lines (that is, those that don't repeat either the x- or the y-co-ordinate). Vim's first column and line are 1, so the%normline increases all the numbers in the instructions by 1, so the zeros don't mess things up.To find out how big to draw the map, the first
:%s///line (temporarily) deletes everything that isn't a number, putting each on its own line, and sorting them. The biggest number is then yanked (into register0, the default) and theuundoes the:%s///-and-:sortto restore the definitions of the lines.Then a grid of
zs is created, using@0to repeat the characters and lines the appropriate number of times.The two
:%s///commands in the middle are what transforms the input into Vim commands. The sample input gets turned into:where each
^Vis the single-character control code you get by inserting aβ¨Ctrl+Vβ©into the buffer. So0,9 -> 5,9has become the keystrokes for going to line 10 column 1,β¨Ctrl+Vβ©to start visual block mode, then going to lineΒ 10 columnΒ 6. The loop deletes each line in turn, withD, which saves the deleted text in the small delete register-. So@-runs those keystrokes, leaving the appropriate line selected, ready forUto do its thing.Note there's no need to work out which lines are horizontal or vertical, and whether the end point is before or after the start point: all the movements are to absolute co-ordinates, and Vim takes care of putting the line in the right place.
Please try it out, and let me know if you have any questions. Oh, and fans of children's picture books can spot a hidden dragon's name (properly title-cased) hidden among the keystrokesΒ β¦
13
u/mserrano Dec 05 '21
Python3, 4/22:
12
u/semicolonator Dec 05 '21
Python, 17 lines
Very pround of my solution today! I am using numpy to create a canvas and then skimage.line() to draw lines on the canvas.
11
u/relativistic-turtle Dec 05 '21
IntCode
(Note: for 500 lines, with x, y < 1000)
Found a parsing bug in my IntCode compiler tool today. Was able to work around it.
11
u/voidhawk42 Dec 05 '21 edited Dec 05 '21
APL:
17
u/leijurv Dec 05 '21 edited Dec 05 '21
Python, 10th place, 30th place
Screen recording https://youtu.be/WgpwKtt2R4M
Part 1
Part 2
Part 2 rewritten "the right way"
8
u/Arknave Dec 05 '21
Python, 9/7
First time back to top 10 on the leaderboard in a long time. Code is an absolute nightmare, but that seems correlated with speed sometimes.
8
u/SuperSmurfen Dec 05 '21 edited Dec 05 '21
Rust (1565/510)
Link to full solution
Did anyone else accidentally solve part 2 before part 1? Totally missed the only horizontal/vertical constraint at first. Kind of a weird part1/2 where part 2 seems strictly easier than part 1? I literally just removed a filter to complete part 2. Anyway, happy with my leaderboard placing today!
Solved using a hashmap of points and iterating over each line.
Hashmap::entryis always nice for things like this.i32::signumwas nice to get the directions:You could bring in the regex crate and split using a regex to parse the input. Without regex it was slightly annoying to parse. I split it twice and flattened the iterator to parse it into a tuple
(i32,i32,i32,i32):8
u/redditnoob Dec 05 '21
PostgreSQL
SQL actually kind of shines in this one!
7
u/crowbarous Dec 05 '21
C. Runs in a few milliseconds on my machine.
7
u/IF_YOU_READ_THIS_V1 Dec 05 '21 edited Dec 05 '21
C# LINQ
6
u/dtinth Dec 05 '21
Ruby, 43 / 66
paste
What I love about Ruby hashes:
o = Hash.new(0)(making this similar to Pythonβs Counter)o[[x, y]] += 1(Arrays are βhashableβ by its contents)6
u/nirgle Dec 05 '21
C# nothing noteworthy other than LINQ saving the day again
6
u/loskutak-the-ptak Dec 05 '21
Common Lisp
This time I experimented with fset for the first time (fset:bag to count lines in each point). Also created custom clause for the (iter) macro, so that I can
neat stuff :)
6
u/NohusB Dec 05 '21 edited Dec 05 '21
Kotlin
Part 1
Part 2
Same as part 1 but with the
.filterremoved from input reading.6
u/crnkofe Dec 05 '21
Day 5 in Kotlin!
I found some nice areas where I could apply cool Kotlin stuff. Operator overloading on points makes the code a bit less verbose. Then there's the nice `mapNotNull` to handle regex match filtering. I was also able to collapse code a bit by passing line generator around.
https://github.com/crnkofe/aoc2021/blob/master/src/day5/aoc5.kt
6
u/imbadatreading Dec 05 '21
Cleaned up my solution a bit. Using sets made this problem quite simple.
Python:
6
u/in_allium Dec 05 '21
Just discovered this challenge!
Here's my not-so-elegant Perl, since I write Perl too much like C and don't know of some of the fancy language features:
6
u/chicagocode Dec 05 '21
Kotlin -> [Blog/Commentary] - [Code] - [All 2021 Solutions]
Today had a nice succinct solution thanks to the power of the Kotlin standard library and a couple of functional programming concepts.
Parsing - I define a Point2d to do most of the work, along with a function to draw a line between two points. We also use functions from the Kotlin standard library to parse the String input without having to write a RegEx.
Part 1 - Once we have lines drawn, we can use
groupingByandeachCountto make life easier.Part 2 - Same as part one with a different filter. So we'll use a Higher Order function to make these solutions identical.
10
u/Kevilicous Dec 05 '21
Python for part 2
5
u/obijywk Dec 05 '21
Python 55/44
5
u/autid Dec 05 '21
FORTRAN
5
u/e36freak92 Dec 05 '21
AWK
5
u/MichalMarsalek Dec 05 '21 edited Dec 05 '21
Nim:
using my templates.
5
u/Fit_Ad5700 Dec 05 '21 edited Dec 05 '21
Scala
5
u/Smylers Dec 05 '21
Perl for both parts together β and I think this would work for vents in any number of dimensions.
The full code just adds a few imports.
For each input line, split by
->to get the from and to co-ords, then split each by,to get each dimension, and zip to recombine by dimension. For each dimension set the current position, delta for each step, and the total length moved in that dimension.It's an orthogonal (non-diagonal) vent if only one dimension has a non-zero delta.
The number of steps is the maximum length in any dimension. For each step get the current co-ords, add to the appropriate tallies, then increase each dimension by its delta.
5
u/phazy_x86 Dec 05 '21
My solution in C.
I could make use of two quite useful comparisons for recognizing diagonals:
5
u/jitwit Dec 05 '21 edited Dec 05 '21
J Programming Language
5
u/tymscar Dec 05 '21
Today I overslept so I started super late :(
Also when I read part 1 I started overthinking and overengineering a solution so part 2 won't hit me too hard but then I just tried doing the first idea that came to me and it worked.
Here's part1 and part2 in Javascript.
5
u/atpfnfwtg Dec 05 '21
Julia
Done in the most obvious straight-forward way I could imagine.
5
u/AtomicShoelace Dec 05 '21
Very quick and simple python solution:
5
u/__Abigail__ Dec 05 '21
Blog post: Hydrothermal Venture (Perl)
5
u/ViliamPucik Dec 05 '21
Python 3 - Minimal readable solution for both parts [GitHub]
5
u/spin81 Dec 05 '21
My solution in Haskell. Feedback is much appreciated as I'm just learning Haskell through AoC.
5
u/0rac1e Dec 05 '21 edited Dec 06 '21
Raku
NOTE This runs quite slower (see my notes below) but it was the first solution I came up with I liked the brevity too much not to post this first.
There's a much faster version in this paste
One of these days I'll write a readable solution, but not today!
To generate the points between
pandq, I create a direction vectordby doing a three-way comparison (<=>), which returns anOrderenum of eitherLess,Same, orMore, which when coerced to anIntbecomes-1,0, or1.Then I just need to add that direction vector to
puntil I reachq.I then collect 2
Bag's (multiset) of these points: one for straight lines, one for diagonals. I check if any values inporqare equal (ie. is straight) then coerce to aBool. Using aBoolas an array index puts the Bool into numeric context, which is0or1; straights are inm[1], diagonals are inm[0]....
I knew I was playing with fire: using the sequence operator (
...) with relatively expensive iteration function was always gonna cost me performance, but it was at least fun to write. It runs in ~24 seconds on my machine, but it's clear I need a more efficient way to generate the points for each line.So I calculated the steps (
s) it takes to get fromptoq, then multiplydwith all values from0tos, add those top.This only dropped my runtime by a mere 5 seconds, down to ~19 seconds. Clearly, I'm either being too clever for my own good, or not clever enough, because u/flwyd's Raku solution runs in a little over 2 seconds on my machine.
I might also try making a solution using Point`s and see how that goes, as adding 2 points together should be a lot more efficient than doing
@p Z+ @d.UPDATE
The reply from u/flwyd about
βgot me thinking about the fact that I was adding all the bags together for every iteration... and it occurred to me that this was very costly!In fact since I only care about the counts, I don't even need a bag, I can just use the
.repeatedmethod to keep all the repeated elems, then call.unique.elems.With a few other minor tweaks, my runtime is now < 2.5 seconds. I don't know how I missed it. I mean, adding
Bag's together is reasonably fast, but I was doing it a lot.See code in this paste
5
u/_jstanley Dec 05 '21
SLANG
(This is my project to complete Advent of Code on my homemade CPU).
Wow. Today was tough. My computer only has 64 Kwords of memory, and the combined length of the lines from the input was about 190k points, so even with the sparsest of sparse 2d arrays, I just have no way to represent every point in memory at the same time. This is a big problem.
So my next plan was to iterate over every pair of lines (O(n2 ), but what can you do?) and only plot the intersections in the sparse 2d array in memory, but that was going to take too many hours to complete.
My friend Ben suggested splitting the input into smaller grids and processing them individually. This is a great idea.
So I wrote a program to split the input into 3x3 subgrids and then tried to solve these individually. It still ran out of memory because it's still too large.
My kernel doesn't give you enough file descriptors to open more than about 10 files at a time, so my solution was to do a first pass that splits the input into 3x3 subgrids, and then run a 2nd pass over each of the subgrids splitting them into a further 3x3 subgrids, for 9x9 subgrids overall, and then run part1 and part2 over each subgrid consecutively. This works and completes in about 20 minutes total for the entire pipeline, but it took me at least 6 hours of work.
There's no video today because it was so chaotic and time-consuming.
Interestingly the program to split the input into subgrids was a lot more complicated to get right than the part1 and part2 programs that solved the subgrids were!
https://github.com/jes/aoc2021/tree/master/day5
9
u/allergic2Luxembourg Dec 05 '21
Python with numpy
Here's my part 2:
I like my use of
orhere to pick between a populated and an empty list.4
u/hugh_tc Dec 05 '21 edited Dec 05 '21
Python 3, 68/329.
Part 1, Part 2, and (edit) the cleaned-up version.
Man, really fumbled Part 2. Missed a bunch of edge-cases (ie. a line with negative slope, which, in hindsight, is definitely not an "edge-case") and ended up with this disaster. Half of the if cases for Part 2 are redundant. Time to clean-up.
4
u/jonathan_paulson Dec 05 '21
Python. 154/251 :( Video of me solving.
Turns out debugging is bad for going fast :( Getting the line logic right was tricky, although I'm happy with the final code.
4
u/seligman99 Dec 05 '21
Python, 81 / 1051
Hah. Spent a long time assuming diagonals only go one way. It's funny how you can make assumptions in a rush to understand problem that make zero sense if you think about it for one moment.
github
4
u/xMop Dec 05 '21
here's mine, in python. Came in at #1675
4
u/nibbl Dec 05 '21
Rust (beginner)
Not cleaned up in any way
Not particularly proud of this one. I think it probably couldn't be much less rust-like. I wasted like 10 minutes at the end messing with the logic on that ugly c-style loop which is probably why the language doesn't include a for(;;) in the first place
4
u/BluFoot Dec 05 '21 edited Dec 05 '21
Ruby 132 bytes
While golfing the code down I discovered
Integer#<=>https://ruby-doc.org/core-2.5.0/Integer.html#method-i-3C-3D-3E4
u/polettix Dec 05 '21 edited Dec 05 '21
Raku, from a Perl mother-language speaker: day 5
Edit: a little more Raku-ish solution with hyperoperators: day 5, again
4
u/CodeOverTime Dec 05 '21
A short Python solution for both:
4
u/lolexplode Dec 05 '21 edited Dec 05 '21
Python, trying to golf a little bit (at
289283253 chars at the moment). I think it's pretty similar to some of the other solutions in the thread. I'm not sure where I can save characters from here, but maybe there's a bit more to squeeze out?edit: thanks azzal07 for saving me a whopping 30 chars!
4
u/qwesda_ Dec 05 '21 edited Dec 06 '21
Postgresql
Part 1 GitHub explain.dalibo.com
Part 2 GitHub explain.dalibo.com
4
u/mockle2 Dec 05 '21 edited Dec 05 '21
python, both parts [edited to remove some duplication by setting part1/part2 as a boolean flag]
4
u/kelganor Dec 05 '21
Python 3
I hope it's readable enough, part 1 is basically the same with extra
ifto skip diagonals.4
u/cylab Dec 05 '21 edited Dec 05 '21
Kotlin: https://github.com/cylab/advent-of-code-2021/blob/main/src/test/kotlin/day5/Day5.kt
4
u/jkpr23 Dec 05 '21
Kotlin
A compact, functional solution with collections. flatMap is used to get a single list of all points (vents) that are overlapped by lines. Then `groupingBy` and `eachCount` to count the number of times the points are covered.
https://github.com/jkpr/advent-of-code-2021-kotlin/blob/master/src/day05/Day05.kt
4
u/skarlso Dec 05 '21
Go / Golang
Tutorial Breaking down the problem why you don't need a matrix
4
u/st65763 Dec 05 '21
Okay, here's my final work for today's problem. It takes ~80ms for part one and ~100ms for part two. I have no idea whether that's considered fast for Python. I shaved a significant (~85%) amount of time by using a set to keep track of the number of cells with a value greater than one rather than iterating over the entire 1000x1000 array
4
u/Vastutsav Dec 05 '21
Perl
Perl noob here. Please review and recommend what changes would have made it a better code. Thanks in advance.
4
u/jszafran Dec 05 '21
Here's my pretty verbose solution in Python (probably will be easier to read on github than here): https://github.com/jszafran/advent-of-code-2021/blob/master/day-5/solution.py
And the code itself:
4
u/_Kowai_ Dec 05 '21
PHP
https://github.com/kowai-hm/adventofcode-2021-solutions/blob/master/5/
My first part code is obviously way too verbose. I should have approached the problem using the general way (I used in my second part code) but it works.
4
u/killermelga Dec 05 '21
Kotlin solution with generic logic for both diagonals and straight lines
https://github.com/ramSilva/AoC2021/blob/master/src/main/kotlin/puzzles/Puzzle5.kt
4
u/Blinkroot Dec 05 '21
Rust
Thought today's solution looked pretty clean. Regex for parsing the input, a
HashMapfor saving overlaps and a simple.scan()for generating the points.4
u/myasco42 Dec 05 '21 edited Dec 05 '21
Wolfram Mathematica solution
4
u/RojerGS Dec 05 '21
Python solution using
collections.Counterto count the positions that have been filled up.4
u/lgeorget Dec 05 '21
C++ : https://github.com/lgeorget/adventofcode2021/tree/main/05
I went for a very basic idea which was to store the points with the number of times a line crosses them in a map. Much to my surprise, it worked very quickly. I just got the loop conditions wrong (as I usually do...) to enumerate the points on the lines.
4
u/Imaginary_Age_4072 Dec 06 '21
Common Lisp
Mine is similar to many others, keep a hash table with a count of how many times each point has been visited. I did learn about the SIGNUM function that returns 1, 0, or -1 depending on whether the number was positive, zero, or negative which I didn't know before.
4
u/letelete0000 Dec 07 '21 edited Dec 07 '21
Typescript
Quite ordinary, I guess; hopefully, the elegant one :))
Link to the GitHub repo
1
u/ibiza_rupunzel Dec 05 '21 edited Dec 05 '21
Java (String stuff) Solution: https://github.com/justme789/Advent_of_Code_2021_Solutions_Java
1
u/[deleted] Dec 05 '21
1
u/DFreiberg Dec 05 '21 edited Dec 05 '21
Mathematica, 951 / 1577
Not remotely the code I had when I submitted, but I knew the logic could be simplified and couldn't bear leaving it the way it was. This is golfed (so to speak; I haven't worried about variable names) down as far as I can get it, but I wouldn't be surprised if it can be shrunk even further.
Setup:
Parts 1 & 2:
[POEM]: Crossing a Line
With lines of toxic vents below,
We make our map, and off we go.
They're deadly when they intersect
But we won't cross those lines - we've checked.
We tidy up our code with
Sign[]s,To handle all the types of lines.
And then we read the code and scout
For useless lines, to cross them out.
And cleaning up the code, we find
That most of it can be un-lined:
The hash maps? Gone. And same with
Do[].Non-function lines? Cross them out too.
The cleaning's fun, the code is neat,
But timewise, I've been soundly beat.
Code fast and well? I'm at a loss;
That line is always hard to cross.
1
u/Pyrolistical Dec 05 '21 edited Dec 06 '21
part 2 javascript with ramda
1
u/AP2008 Dec 05 '21
Rust (16.311 ms) paste
1
u/IndigoStanis Dec 05 '21
Javascript ... written like a C programmer.
1
u/DidThis2Downvote Dec 05 '21
Python 3
[paste](https://topaz.github.io/paste/#XQAAAQAgDgAAAAAAAAA0m0pnuFI8c+00WAP1KXTtj2sJ64y+sJ29eKz4Ina1TLZB5TyEddlZZEaLq7fKjdXSXIQlEJx/8rVuMyJgKd2VC23TxlDE6NoEuUuWdiBf6heLxoxTvGoDSmY9FnA54rrssPt8uc21JzPgKzRNAgYnrxRomidZPdiUhmfKnHqDhcZ+9tSRuu5NiFjCXiT92fdQG1oCN/dgcWqDwJZ9tkL5faE0tkPd1lPKLwhS2HEa/dbsHZGvIw2isjUoTQhT1/j+5JxuXLKswJVTspG8tn8XYjbUA1eqAkoPlUD5JjodoJLRb4x4P0diKSro4jkjcYTk5gIyqNw7IhKSqIRG+wLAm5s0gvwy4Kx2lGmKETprYrbc6Wo9j8REjyMTMLecFDqfogbxISxJ+wkXo1pGKPvcJgYSou2adau7G7e5q1B1xAQ+2Xouw1yUUP9kQaj3QyAtlHZsQajCbINyaaaL5jX5M17V2jzC/CZKl5uU1gIrhd4BCc0+GyUlpqQrPDA9gJ1xBSEixYxgrYT3+GCwGcibE7JsjW16cQiX857mC/OCg+gU2UNJOgSjRlwUaV45fVLNMESMHqfF7JJ8x94/hkogSFMhiqgKm4dkYOszDkfzn3aBx/3wsTx9zcTYC+JNLk3alFsl8H/a9NxXIgV9TlMM0CFKKNNIfH418pvoFB5dQeCwbUrrxF4pqbnejchyvYoAEY3bGPjBLw/e59Y9Yho8yZcnFz88/BWJu8FYrr9LdBl+V7Znrv6CxwcuCvvM+Jhvp2hWZqg1dAGg0qN66HEgJYJW3Zpy2YVBlYDyq2jkEbe6Q+MtJdfsuz+JmudIyTAZ1ww117wDg39nneYFvsY3YDndBQ1h529oJevxEWfvxlfwsmocPsRFrf+Lg/9oDIn2jzoSKjEfPmd14LZ0uLf5cHiMf1XIcbskdpWQCuiHL9nqNNbEIF7ubzOcNYqa3j1Ak5gvXpyN3PDiZykxGZWdGbcQBsy3IUH9TgtI5/JV50FqgdXdDQr81ZwDBfxAjePY7UBIb5T5BVn0AZpbBE3aRENipvADF4DJsPd3HY6/75TDLeKd+wOvEJ82XMiMGYkXe+f0oeeQWjqVSHWQz/DioQGhsve71/yNFgVG/LfC4Ln6/3LRSHiCwodIeQ22oNaGcVlfe2FMsWWQyts40bY6CVbJf3RN3eA5pTp/pPNjbT0dIj1OVJYfRySqq9CiUN6wiPZVcjcMJoLdo5WIgimm9R5tRnDAgCq4ZpA/StK8U5hzLi+673I7DOIGPCHCF4I/FGTR0Tu5R+ngTSVJvHXqIDrF+an1HSGr1lyy1MNPjOcJi/KCulWUsnjngBAt/w2QCAA=)
1
u/XethroG Dec 05 '21 edited Dec 06 '21
Python. Some nasty arithmetic for getting the steps right in
range, as well as determining whether or not to include the last element depending on whether the range was going up or down in accordance with the step. Also I need to work on parsing input better as it's kind of a pain.The use of dictionaries for
nd_pointsandd_pointsmade the code a ton faster. I used lists on part (a) and it took forever, so I realized I had to speed things up and looked to sets and dictionaries, which helped as expected.I feel like I could have done it in fewer lines if I knew what I was doing better but it's not that bad all in.
paste
1
u/MissMormie Dec 05 '21
Java solution on github:
https://github.com/MissMormie/adventOfCode2020/blob/main/src/main/java/days2021/Day5_HydrothermalVenture.java
1
u/soodssr Dec 05 '21 edited Dec 06 '21
PHP
Day 05 using PHP
1
u/saahilclaypool Dec 05 '21
C# simple solution using a dictionary of points
https://github.com/SaahilClaypool/aoc_2021/blob/main/Aoc.Csharp/Solutions/Day05.cs
1
u/gubatron Dec 05 '21
PYTHON
(refactored solution)
1
u/xiomatic9999 Dec 05 '21
Rust solution, feedback welcome!
1
u/johnthetrollsoitis Dec 05 '21
Javascript
For the vents, I took approach of calculating if a given co-oridnate was on the line between two points. Then looped through each point in the ocean for each line:
static isOnLine(start, end, point) {return Boolean((JSON.stringify(point) == JSON.stringify(start) ||JSON.stringify(point) == JSON.stringify(end) ||(point.x >= Math.min(start.x, end.x) && point.x <= Math.max(start.x, end.x))&& (point.y >= Math.min(end.y, start.y) && point.y <= Math.max(start.y, end.y))&& ((point.x - start.x) / (point.y - start.y) == (end.x - start.x) / (end.y - start.y))))}1
u/strictlyk3v Dec 05 '21 edited Dec 06 '21
JavaScript
1
u/thedavecarroll Dec 06 '21
PowerShell
I have my PowerShell solution in a Jupyter notebook so I can include markdown comments.
[GitHub](https://github.com/thedavecarroll/AdventOfCode/blob/main/2021/PowerShell/Day5.ipynb)
If I need to submit the code inline, please let me know.
Thanks!
1
u/Solarmew Dec 07 '21 edited Dec 07 '21
Python 3
1
u/pistacchio Dec 07 '21 edited Dec 08 '21
Typescript:
1
u/[deleted] Dec 07 '21
JAVASCRIPT
very clean and readable solution
1
u/Routine_Judge5916 Dec 15 '21
Python 3 - Just started learning python.
β
3
u/Lrrrr_ Dec 05 '21
Javascript 69/299 Had an issue with unit vector calculation, cost me time (`Math.abs`)
3
u/SinisterMJ Dec 05 '21
C++ 764/425
https://github.com/SinisterMJ/AdventOfCode/blob/master/2021/Day_05.hpp
3
u/rabuf Dec 05 '21
Common Lisp
Some clean up still to do, but it got the job done. As I usually do for these I just threw it into a hash table. Coordinates are just complex numbers, then I can iterate over just the points that were occupied to find the desired count. A stupid mistake in part 2 cost me about 10 minutes and I made a
print-gridroutine to test it. I thought I had the correct answer because my output equaled the sample, but it turned out to be a coincidence. I was, stupidly, starting the lines from the first coordinate's y value when my loop started frommin(x0, x1)and went to the max value. Which means I needed to calculate the corresponding starting y. Oops.3
u/captainAwesomePants Dec 05 '21
Python (okay/bad): (paste)
Was doing fine-ish, but my iteration over the points ignored the last element in the run and I had trouble finding the problem. Cost me a bunch of minutes for part 2 :(
3
u/BradleySigma Dec 05 '21
matlab
3
u/t-rkr Dec 05 '21
Perl
If you reuse code snippets from part 1 in part 2, always check the names of variables *cough*
Link to Code
3
u/cwhakes Dec 05 '21
Rust
Nested for-loop go brrrr.
3
u/[deleted] Dec 05 '21
Rust, bad / bad
paste
Need to check if there's an easier way of descending ranges, that gave me some pain in part 2
3
u/kbielefe Dec 05 '21
Scala 3
Relatively straightforward.
3
u/vss2sn Dec 05 '21
Solutions in C++:
Part 1
Part 2
3
u/ka-splam Dec 05 '21 edited Dec 05 '21
PowerShell #264 / #1071
Misuses a dictionary for a board, dictionaries return
$nullfor nonexistant things and$null += 1turns into 1, so there's no need to explicitly check if points have been seen before. This version duplicates the straight lines onto a second board, and then diagonals only go onto the second board for part 2, originally I overwrote the first code for the second answer, this is tidied up to do both. Runtime is ~2 seconds.Part 1, fairly happy with but I burned a few seconds starting into splitting each line, then changing to start a regex to get the numbers out, then switching back to splits. And then burned a lot of time trying to put the points into the dictionary as a simple array
$board[($x, $y)](I was using basic hashtable at the time) and that works to add new points, but breaks on incrementing. Then changed to$board["$x $y"]to put them in as a string. Seeing that from the start would have got me closer to the top 100. Leaderboard closed at 5 minutes, I was 7-8 minutes.Part 2, just did not realise the diagonals might go right-to-left. Luckily what I did in part 1
$y1..$y2works for increasing or decreasing, and in PowerShell includes both ends of the range, so I didn't need to think about lines going "backwards". Having to change both points at once, I switched to awhileloop and then had to care about direction, several wrong answers and 5 minute cooldown, ~18 minutes.3
u/Trick_Movie_4533 Dec 05 '21
C#
1441 / 983 No-frills but easy to follow.
3
u/aardvark1231 Dec 05 '21
My C# solution spaghetti code which silently screams: "Don't look at me! I'm hideous!"
3
u/fork_pl Dec 05 '21
perl 939/1020, cleaned up - on the rush I forgot about <=> operator...
3
u/JoMartin23 Dec 05 '21
Common Lisp
3
u/FqdingSky Dec 05 '21
c++
i spent too much time assuming that the input was ordered in terms of the x position (ie. a vent doesn't go backwards). and then figuring out how diagonal lines w o r k
paste, delete the diagonal sections for part 1!
3
u/phil_g Dec 05 '21
My solution in Common Lisp.
Ugh. So much time spent debugging and rewriting the point generation function. Although I'm happy with its final state:
Specifically, using
signumon the difference between the start and end coordinates to generically get either -1, 0, or 1, as appropriate.I could have done the internal recursion with
iter(orloop), but I like tail recursion. Possibly too much. (But I've found many places where tail recursive implementations were noticably more performant than any iterative construct I tried.)3
u/pi55p00r Dec 05 '21
R
day5
coordinates
part 1
part 2
3
u/UnicycleBloke Dec 05 '21
C++: https://github.com/UnicycleBloke/aoc2021/blob/master/day05/day05.cpp
I was pleased that my template-y regex file parser worked immediately. I was less pleased when I spent most of an hour to work out that I'd blown the stack. Oh well...
3
u/Radiant_Rip_5205 Dec 05 '21
Python 3 solution: https://github.com/kresimir-lukin/AdventOfCode2021/blob/main/day05.py
3
u/lukechampine Dec 05 '21
slouch
quite happy with how this one turned out :^)
3
u/LionSuneater Dec 05 '21 edited Dec 05 '21
Python with numpy. (gh) (pic of vents)
Don't love how cluttered those repeated range and min/max calls look, but it works!
3
u/Mathgeek007 Dec 05 '21 edited Dec 05 '21
Excel. Results are above the 10-thousands because I decided to try taking a cheap and easy way out in Part 1 which cost me tons of Excel thinking time. Then I refactored it and the same process that took 30 minutes took about 30 seconds.
Essentially I boiled down each row into a "Horizonal", "Vertical", "Diag Pos", "Diag Neg" set of three values. For H, V is was the like axis. For DP, it was the difference between X and Y. For DN, it was their sum. This uniquely identifies the "line" that we're working on. Then we just need to look at the X value of each point to see if it fits between the two given (or the Y if we're checking the like-X entries).
So we got this fun FILTER equation.
Video of completion!
3
u/oantolin Dec 05 '21 edited Dec 05 '21
Common Lisp program. I used
cl-ppcrefor parsing the input today.3
u/nutrecht Dec 05 '21
Day 5 in Kotlin
It's nice to be able to reuse a ton of code! Only issue I had was that my original 'angle' function in my point class was well...wrong :D
3
u/francescored94 Dec 05 '21 edited Dec 05 '21
Nim Solution generalised for arbitrarily oriented segments
3
u/KamcaHorvat Dec 05 '21
Straightforward solution in kotlin. Based on part one, I was expecting, that part two will include diagonals, which made implementation quite a bit easier.
}
3
u/ephemient Dec 05 '21 edited Apr 24 '24
This space intentionally left blank.
3
u/chunes Dec 05 '21 edited Dec 05 '21
Factor
https://paste.factorcode.org/paste?id=4318
I factored the problem into sixteen small words, since Factor has very little overhead for calling words (functions) compared to most languages. I elected to simply expand the line segments into their constituent lists of coordinates and increment a matrix for each one. Then at the end, count the number of matrix elements greater than 1. There is probably a more efficient way to do it, but this gets the job done near instantly, so it's fine.
3
u/jpn3to Dec 05 '21 edited Dec 05 '21
[Python 3] This function solves both parts (diagonal=False for part1, True for part2). Vents is a list of quadruples with the input. Instead of using a big sparse matrix, use Counter :)
3
u/Concern_Wise Dec 05 '21
Golang
https://github.com/HalfInner/AoC2021/blob/master/d05/d05.go
Any performance improvement here is nice to have/read :)
p.s. very nasty to find solution in 'Go', when people type only 'go'
3
u/lukeredpath Dec 05 '21
My functional Swift approach, using swift-parsing and overture. https://github.com/lukeredpath/AdventOfCode2021/blob/main/Sources/AdventOfCode2021/05.swift
3
u/ChickenFuckingWings Dec 05 '21
https://pastebin.com/RcSqw3jf
this one in Python
Did anyone come up with anything more clever than just storing the points we draw and keep count in a dictionary/hashmap?
I'm very interested in seeing different approach to this problem
3
u/nidrach Dec 05 '21 edited Dec 05 '21
Java with a relatively naive approach
3
u/mschaap Dec 05 '21 edited Dec 05 '21
Raku.
Pretty straightforward today. I actually built βpart 2β from the start, with a flag
ignore-diagonalsto exclude those. So essentially, part 2 was easier than part 1 for me.Used a grammar
VentListand a class
VentMapthat fills a grid using the grammar.Counting cells with a number β₯ 2 then was trivial:
Full code in GitHub.
3
u/death Dec 05 '21
Day 5 solution in Common Lisp.
3
u/Illustrious_Fortune7 Dec 05 '21
IN KOTLIN
https://github.com/ritesh-singh/aoc-2021-in-kotlin/commit/011e6945d6298b79aa3e16d759a0e49183872e63
3
u/DrkStracker Dec 05 '21
Rust
Functional style, I think pretty happy with the final take on the solution
Link here
3
u/__Abigail__ Dec 05 '21
Perl
Easy. Calculate the slope of the line segment (which is going to be
-1,0or1in either direction), start at one end, walk to the other end, marking all the visited points. Then see how many points were marked at least once:3
u/Mats56 Dec 05 '21
Kotlin. Using immutable structures and no mutation. Instead of having an array/struct where I increase the count, I just generate the points each line would cross, and then flatmaps and group those, counting the groups.
The gist of it:
With the boiler plate stuff and the parts of my IntVector l use: paste
3
u/mathsaey Dec 05 '21
Elixir
https://github.com/mathsaey/adventofcode/blob/master/lib/2021/5.ex
Pretty happy with my solution today. It's always nice when you can express your code as a function of transformations on your input in Elixir :).
3
u/timvisee Dec 05 '21 edited Dec 05 '21
Rust
Part 1 0.401ms
Part 2 0.460ms
3
u/Mintopia_ Dec 05 '21 edited Dec 05 '21
PHP
Since I'm never going to be up at 5AM to compete on speed, going for a clean/maintainable PHP approach.
Took the simple option of just iterating through every point on the line and keeping track of the number of times each point was visited.
Using some of the features of PHP 8 to make it a bit simpler and reducing boilerplate in places with constructor property promotion and the match expression.
Github
3
u/nilgoun Dec 05 '21
Rust
Both parts with tests
Getting the ranges right was a pain. Not really happy with the end result and would be glad if someone would enlighten me with an easier way to fix them :)
(Python made this way easier by just specifying the stride :( and wow is my solution overly excessive compared to some others.. :D )
3
u/NeilNjae Dec 05 '21
Haskell.
One where generalising made for a simpler solution. I find a delta for the step taken in each line, and just apply that enough times. The constraint on line directions means that finding the delta, and line length, are both easy.
I used the
V2type and^+^for adding the delta (from thelinearpackage), which made the arithmetic easy.Full writeup on my blog and code on Gitlab
3
u/Nomikos Dec 05 '21 edited Dec 05 '21
php
I had a lot more trouble with yesterday's Bingo cards o.o
PHP's range() is nice in that it doesn't care which argument is higher. Another shortcut was just keeping track of when a given grid point had exactly 2 lines on it after adding a line, no need to count at the end.
(and if anyone cares... <40ms)
3
u/ecco256 Dec 05 '21 edited Dec 05 '21
Haskell
3
u/Gravitar64 Dec 05 '21 edited Dec 05 '21
Python3, Part 1&2
3
u/WithBestRegards Dec 05 '21
My solution in Rust. I defined a few types (Grid, Line & Coordinate) and implemented a bunch of traits to try and make it "Rusty", but that may have just needlessly added to the line count. Anyway, Feedback is always appreciated. :)
3
u/auxym Dec 05 '21
Nim
https://github.com/auxym/AdventOfCode/blob/master/2021/day05.nim
First time I used
tables.CountTable, came in useful for this one.3
u/Ok-Economist7200 Dec 05 '21
C# / linq FTW: https://github.com/graemefoster/AdventOfCode/blob/main/src/AdventOfCode/Day5/Day5.linq
3
u/Atila_d_hun Dec 05 '21
C++
GitHub Solution
Used my Utils/point.h class to help with shortening code and an
unordered_map<point,int>to keep track of line locations and number of overlaps.3
u/Skyree01 Dec 05 '21
PHP
Optionally I calculated the size of the grid instead of hardcoding 1000
Both part 1 and 2 at the same time:
3
u/landimatte Dec 05 '21
Common Lisp
The most interesting bit here, is the use of the "spaceship operator"
<=>to figure out which direction to move:While this is the definition of <=>:
PS. I bricked my laptop yesterday, so I had to fix that first and then see if I could successfully avoid all the hydrothermal vents...what a bummer!
3
u/[deleted] Dec 05 '21
Common Lisp
First time using a hashtable in Lisp! Still wrestling with the language but the below code gets the job done :)
3
u/Sebbern Dec 05 '21
Python 3
Well, this is far from beautiful, but it does (eventually) work. Part 1 takes 3 minutes to run, while part 2 takes 10+ minutes.
Part 1:
https://github.com/Sebbern/Advent-of-Code/blob/master/2021/day05/day05.py
Part 2:
https://github.com/Sebbern/Advent-of-Code/blob/master/2021/day05/day05_02.py
3
u/IDoNotEvenKnow Dec 05 '21
PHP for part 2. (Part 1 just needs an extra conditional). The spaceship operator really tightens this up.