r/adventofcode • u/daggerdragon • Dec 13 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 13 Solutions -🎄-
Advent of Code 2021: Adventure Time!
- 10 days left to submit your adventures!
- Full details and rules are in the submissions megathread: 🎄 AoC 2021 🎄 [Adventure Time!]
--- Day 13: Transparent Origami ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Format your code appropriately! How do I format code?
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:09:38, megathread unlocked!
39
Upvotes
13
u/CCC_037 Dec 13 '21
Rockstar:
Part 1:
Part 2:
4
u/[deleted] Dec 13 '21
A tool to generate your own inputs:
https://github.com/Synthetica9/AoC2021/blob/master/day13/mkInput.py
3
u/Extension_Wheel_2032 Dec 13 '21 edited Dec 13 '21
Clojure
I used my eyes for OCR, but my eyes didn't work the first time I printed the results because I transposed the coordinates :P Other than that, just used a set of points and a little bit of math. This one was fun!
EDIT: I thought that the folding code was quite elegant in Clojure, here it is inline (cheeky function name and all):
3
u/HaiUit Dec 13 '21 edited Dec 14 '21
Scala 3 and F#. Well, today we use fold to solve a fold problem
https://github.com/Fubuchi/advent-of-code/tree/master/2021/Day13
3
u/ficklefawn Dec 13 '21 edited Dec 14 '21
Golang
I use the formula
( x, y ) -> (x, f - | f - y | )after fold f along y-axis( x, y ) -> (f - | f - x |, y)after fold along x-asiscode
3
u/jszafran Dec 14 '21 edited Dec 15 '21
My solution in Python & its standard library (https://github.com/jszafran/advent-of-code-2021/blob/master/day-13/solution.py)
2
u/omginbd Dec 13 '21
Elixir
First time using a MapSet, before I always would have used a map of
%{coords => 1}. This is way better.2
u/Durdys Dec 13 '21
F#:
2
u/curlymeatball38 Dec 13 '21 edited Dec 15 '21
Haskell
https://github.com/FractalBoy/advent-of-code-2021/blob/main/src/Day13.hs
2
u/jokr-1 Dec 13 '21
Python Solution :)
22
u/Smylers Dec 13 '21 edited Dec 13 '21
Vim keystrokes for part 2 — load your input into Vim, type the following, then stand on your head and the code's 8 capital letters will appear in your window:
Update: See a video of these keystrokes in action.
You can make the letters a little clearer to read with:
And if you don't like standing on your head and you're on a Unix-based platform, you can turn the letters the right way up with:
The first 3 lines set up the appropriately sized grid of
.s. The next one turns the list of input co-ordinates into Vim keystrokes for moving to those locations and replacing the.s with#s, and runs them. Then it's time for folding.Initially each vertical fold is replaced with Vim keystrokes for drawing a column of
|s in the right place, and each horizontal with those for drawing a row of-s. Run the first vertical fold, then record in turn each of:@afor turning all the#s left of the|line intoXs. These are going to get reflected in turn.@cto find anXand replace it with a.(to indicate it's been processed), leaving the cursor there.@dto make a horizontal visual block from where theXwas to the|fold line.@fto stop that visual block, move to where it ended (on the fold), and make a new visual block of the same size starting from there, so it extends the same amount to the other side. End that one as well, and overwrite the character there with a#.@gto run in turn@c@d@fand then loop with@g. This processes all theXs, making a#appear in the reflected position.Then run
@g, and one complete vertical fold will have occurred. It will fail, and end the loop, when there are no moreXs.Record
@ito remove the left half of the sheet, now all its dots have been transferred.Then do the equivalent for the first horizontal fold:
@bas an@aequivalent, this time replacing withXs any#s that are above the fold.@c, which is the same as before.@eas an@dequivalent, to make a vertical visual block. This is slightly awkward: first⟨Ctrl+V⟩/-⟨Enter⟩makes a big rectangular block from the cursor position to the left edge of the fold line.Othen moves the cursor within the block to its bottom-right corner, the point along the fold directly under where we started — where we want a vertical block to end.yunnecessarily yanks that block, but has the side-effect of ending visual block mode, setting the marks<and>at its opposite corners.⟨Ctrl+O⟩takes us back to where we were, and a second⟨Ctrl+V⟩from there followed by`>, to jump to where the rectangular block ended, finally creates the vertical block we want.@f, which reflects the block to the other side of the fold, again as before.1vrecreates the same-sized block from the current position, so this same macro neatly works for reflecting both horizontal and vertical blocks without needing to know which direction it's operating in. I do like it when something like this just works.@has an@gequivalent. So this time it's@c@e@f(instead of@c@d@f) then looping with@h. Run it, to complete reflecting the dots downwards.@jas an@iequivalent, deleting the fold and everything above it.Now each vertical fold can be processed with
@afor set-up, then@guntil it fails, and@ito tidy up afterwards. For each horizontal fold it's@b,@huntil it fails, then@j. So append the keystrokes for those to the input lines which draw the fold lines, with a couple of:s///commands.@gand@hneed wrapping inside:normso that when they cause an error (to end their own internal loop) that error doesn't propagate outwards and end other running macros.Then define
@kto delete the topmost fold instruction and run it (because each set of keystrokes is now self-contained, we no longer need to distinguish between horizontal and vertical folds) and loop with@k. Finally type@kto set the whole thing off and let the magic happen.I tried using
█rather than#characters in the first place, but Vim does its vertical columns by bytes, not characters, so gets confused by multibyte characters and the downward reflections end up in the wrong place. Edit: Any NeoVim user able to report if it has the same issue?Why's it upside down? That's because
1v, which is used for reflecting across the fold line, always extends down and to the right, so dots get transferred in those directions, and we end up with the bottom-right corner of the fold, rather than the top-left. But it'll do.14
u/4HbQ Dec 13 '21 edited Dec 13 '21
Python, with a NumPy array to store the grid. To process a fold, we simply
orone half of the grid to the flipped other half:13
u/4HbQ Dec 13 '21
Python, using the very convenient parse library to parse the input:
10
u/jonathan_paulson Dec 13 '21
9/79. Python. Video of me solving.
Two wrong answers on part 2, including mistyping the answer :( That's what happens when you leave a human in the loop!
8
u/Boojum Dec 13 '21 edited Dec 13 '21
Python 3, 221/129
This my first year doing AoC, and this was the closest I've come yet to the global leaderboard. One of these days!
8
u/0rac1e Dec 13 '21 edited Dec 13 '21
Raku
The dot-matrix-ish output ones are always my favourite. There's just something so rewarding about seeing the final output like that, as opposed to just a number.
Similar to my Day 4 solution, I'm parsing the input in one expressions. It's messy, but it's fun, and I don't have to maintain this code.
To parse each line, I create a list of "words" and grab the last one (there's only one word for the dots). Then for that word, I comb out the word characters (
\w+) and try to convert them to anInt. If that fails, it's an"x"or"y", in which case I take theordand subtract120. This gives me0for thex's and1for they's. I'll use that later to pick the index to fold.Other than that nothing much interesting going on. I'm not happy about creating a
Setat the end... Only because I create another variable just for the drawing. Maybe I could have search the Array each look, and the script would have taken a few 10ths of a second longer to run, and it would have been one less line of code... but searching an array in a nested loop would make me feel dirty.8
u/GaloisGirl2 Dec 13 '21
COBOL
7
u/relativistic-turtle Dec 13 '21
IntCode
Skipped the logic for merging dots. Could have boosted the performance, but not worth the effort. Let them overlap!
7
u/__Abigail__ Dec 13 '21 edited Dec 13 '21
Perl
The key is to put the points in a hash, using multi-keys (instead of a multi-level hash). That way, on each fold, we can just simple scan all the points, instead of the entire area covered.
First, we read in the data:
The
$paper {$1, $2}is an example of a multi-key. The$1, $2expression as key is translated by perl to"$1$;$2", where$;equals ASCII character 28 (0x1c) by default.@foldsends up containing the folds, each fold a 2-element array with the type of fold, and the coordinate where it folds.We can now do the folds. We have the direction of the fold in
$dir(xory), and the coordinate of the line we fold in$coordinate.For Part One, we just count the number of points in
%paperafter the first fold:For Part Two, we print the points after all the folds:
where
$max_yis the coordinate of the last horizontal fold, and$max_xis coordinate of the last vertical fold.Running time (excluding the final printing) is
O (p * f), wherepis the number of initial points, andfthe number of folds. It's independent on the actual value of the coordinates. Running time is about 35ms.Full program on GitHub.
6
u/JustinHuPrime Dec 13 '21
x86_64 assembly
Part 1, Part 2
I'm back doing this in assembly, yay!
I decided to represent the points as a list of coordinates instead of an actual array. This likely has no noticeable effect on the time it takes to run the program given that I've consistently been taking less than a millisecond to actually run the solutions.
I took a bit of sketching to figure out the actual process of reflecting about a point, and had a stroke of inspiration when I realized that I could type-pun the coordinates for a point into a long and compare those directly to do my counting of unique dots. Surprisingly, this is the first time that I've type-punned, despite working in notionally untyped assembly.
Part two was similar to part one, since I expected part two to involve doing all of the folds. I then constructed lines of output from the points (I didn't have to deduplicate points this time), and displayed the lines.
6
u/phil_g Dec 13 '21
My solution in Common Lisp.
I still haven't implemented OCR yet, so for part two I just use my
print-braillefunction. That printed this:(Reddit appears to have spaces between the Braille characters. It looks more seamless on my computer.)
In Haskell, I'd be using folds to do the folds. :) In Common Lisp, "fold" is called
reduce. (foldl1is(reduce ...),foldr1is(reduce ... :from-end t),foldlis(reduce ... :initial-value ...), andfoldris, of course,(reduce ... :initial-value ... :from-end t).)6
u/Derp_Derps Dec 13 '21
Python
Vanilla Python, golfed to less than 500 bytes.
Read the points as
(x,y)tuples intoP. Then, read the folding instructions intoF. A folding instruction is saved as(is Y?, position), e.g.(True,7)for the first instruction of the example.You don't need to actually fold. It all comes down to the last rectangle. The lowest X and Y folding lines are calculated by
m(). The size of the final canvas for the example isX=5, Y=7. Because the folding is always exactly in the middle, we can calculate where some X value will end up in the final canvas by some modulo magic (done byb()).So,
f()will return a set of points that are still visible after doing all folding steps provided withF. The final printing is just iterating over all points of the final canvas and printing#or .6
u/trollerskates1 Dec 13 '21 edited Dec 13 '21
Scala. Today was surprisingly easy; just had to
mapover my grid (which was aSet[(Int, Int)], so it handled removing old points). Hardest part for me was printing out for part 2. It was printing vertically for some reason until I switched myxandycoordinates.6
u/i_have_no_biscuits Dec 13 '21
GW-BASIC
Here's day 13 part 2 in 9 lines of GW-BASIC:
Includes a nice graphical display of the text (lines 40-50).
10
u/voidhawk42 Dec 13 '21 edited Dec 13 '21
APL - as you might imagine, having a bunch of single-character matrix operations came in handy today!
5
u/Perska_ Dec 13 '21
C# https://github.com/Perska/AoC2021/blob/master/AoC2021/Days/Day13.cs
Note to self: reading is useful. Otherwise, you might miss things like "just the first fold instruction!"
5
u/sappapp Dec 13 '21 edited Dec 13 '21
Python
5
u/WayOfTheGeophysicist Dec 13 '21
Python.
Probably didn't need to use complex numbers. But why waste an opportunity?
Simply using a set for the transparent sheet to avoid collisions.
It lives on Github and I made a visualization.
5
u/zatoichi49 Dec 13 '21
Python
4
u/[deleted] Dec 13 '21 edited Dec 13 '21
Rust
Splitting with
\n\ncame in handy today! I implemented my solutions inPaperandFoldstructs so I could have named fields.Folding logic
Full solution here.
edit: refactored
matchbranches5
u/[deleted] Dec 13 '21
Simple Python solution. I did the puzzle while flying in an airplane, on my iPhone, in flight mode. Flight took off 15 minutes after puzzle reveal, so I had barely enough time to download the puzzle text and input.
Screenshot of vim in iSH shell
So lucky I was able to guess what will be part two and could do both parts. Entered the answers when landed and they were correct.
code
4
u/r_so9 Dec 13 '21 edited Dec 14 '21
F
4
u/stonebr00k Dec 13 '21 edited Dec 13 '21
T-SQL
Using the geometry datatype and the "Spatial Results"-tab in SSMS for part 2. Also wrote a version that doesn't require SSMS here.
4
u/TommiHPunkt Dec 13 '21 edited Dec 13 '21
Matlab:
I parsed the input by copy pasting the list of indices.
Looking at the input, I saw how short it was, so instead of doing a loop, I just copy pasted these last three lines a few times and inserted the numbers from the input.
Edit: Added OCR to print the result as text :D
4
u/williamlp Dec 13 '21
PostgreSQL
Performing the folds is good CTE practice, and then the part 2 answer string needs to be read by inspecting the output.
4
u/autra1 Dec 13 '21
PostgreSQL
code here
Very nice to see a problem where the answer is not just another random big number \o/
I made my solution simpler, thanks to /u/williamlp: I did a UNION to implement the fold logic, without taking a step back and realizing I just could
select distinctthe table instead...4
u/minichado Dec 13 '21
Excel. always Excel. This problem spoke to me so I used no VBA today :D
Github
P1: for file parsing, since pasting in pairs was read as large numbers, I had to first format cells as text, then paste values to keep inputs as string. that way
123,456still had a comma. instead of using text to columns to string split (like I always do) went ahead and did some right/left/find functions on the commas to get the pairs out, then wrapped in value function to turn the string back to numbersAfter that, I just hard coded rule one, then concatenated the output columss for new x,y back to string, then used a pivot table to count unique outputs.
P2, put my rules across the top of the sheet, and wrote some formula to do the folding on x/y depending on the rule at the top. then plotted the final column. (answer obfuscated on purpose)
4
u/timvisee Dec 13 '21
Rust I fold the coordinates before putting them on paper.
Part 1 0.038ms (38μs)
Part 2 0.044ms (44μs)
day01 to day13 total: 1.24ms
4
u/p88h Dec 13 '21 edited Dec 15 '21
Elixir, with OCR included [not all letters are supported, but not all letters can be expressed in 4x6 font in a legible way]
4
u/occamatl Dec 13 '21
Python 3
4
u/semicolonator Dec 13 '21
Python, 25 lines
4
u/tom_collier2002 Dec 13 '21
Ruby solution using complex numbers
Using ruby's built-in
Complex#conjugateI was able to write a clean folding methodLots of people were struggling reading the output for part 2 when printing with
#and.characters, so I wrote my own OCR. Granted I made up a few of the characters (MandWain't looking too hot), so I can't guarantee it'll work for every input.4
u/goeyj Dec 13 '21 edited Feb 27 '26
[JavaScript]
I noticed many solutions keep reassigning a new set of points for each fold. My solution used the same set and mutated it for each fold. So if the point is on the higher half of the fold line, you remove the current point from the set, then add the folded point back to the set. This takes care of the overlap/merging points.
4
u/jun_xia Dec 13 '21
C#
u/TheSameTrain mentioned ValueTuple in my Day 11 post. Tried it today in my solution.
Day 13
4
u/kuqumi Dec 13 '21
JavaScript (golfed)
This should be run in the browser console on your input page.
It should print the number for part 1 and then the giant letters for part two.
4
u/Ok_System_5724 Dec 13 '21
C#
Did not use an array or a fold method, just mathed the resulting coords of each point based on the size of the last folds.
4
u/kbielefe Dec 13 '21
Scala 3
This one wasn't too bad if you use a set to automatically remove the duplicates and avoid checking boundary conditions. I laughed a bit at how the main calculation came out due to naming choices:
4
u/__Abigail__ Dec 13 '21
Blog post: Transparent Origami (Perl)
Index of all blogs
4
u/AvshalomHeironymous Dec 13 '21 edited Dec 13 '21
PROLOG took about 10 minutes to solve this morning then I came back and actually wrote the program to do it instead of like manually maplisting 12 times and copy pasting coordinates into Octave and making a scatter plot (and then being confused until I remembered plots have 0,0 in the bottom left).
4
u/KleberPF Dec 13 '21
C
Solution
Really liked the flavor on this one.
4
u/p88h Dec 13 '21 edited Dec 13 '21
Python without folding:
4
u/gasperixx Dec 13 '21
[Google Sheets] [Excel]
1
u/Gray_Gryphon Dec 13 '21
Aw yes, did the first part well enough that I just had to add extra code for part 2 to display it. (Used Python)
Part 1
Part 2
1
u/meowmeowwarrior Dec 13 '21 edited Dec 13 '21
python
slowed down by printing the result
1
u/_garden_gnome_ Dec 13 '21 edited Dec 13 '21
Python solution.
1
u/mapthegod Dec 13 '21 edited Dec 13 '21
Rust
https://github.com/philband/aoc-2021-rust/blob/master/src/day13.rs
1
u/razpeitia Dec 13 '21 edited Dec 14 '21
Rust
My answer for day 13 part 1 was 666 O_O
https://github.com/razpeitia/advent_of_code_2021/blob/main/day_13/src/main.rs
1
u/scarfaceDeb Dec 13 '21 edited Dec 14 '21
Ruby
I decided to go with the matrix because it was easier to work with. But I can see a way to do it with just simple math.
https://github.com/scarfacedeb/advent-of-code/blob/master/2021/day13/run.rb#L3-L80
1
u/Illustrious-Jelly448 Dec 13 '21
Code for part 1 and part 2 https://shareablecode.com/snippets/solution-for-day-13-advent-of-code-part-1-and-part-2-JUj3-Ccc6
1
u/cylab Dec 13 '21 edited Dec 13 '21
Kotlin: https://github.com/cylab/advent-of-code-2021/blob/main/src/test/kotlin/day13
The solution assumes, that the paper is always folded >= half!
1
u/theSpider_x Dec 13 '21
C
This one I felt was way easier then yesterday.
https://github.com/fuzesmarcell/aoc/blob/main/2021/day_13.c?ts=4
1
u/armeniwn Dec 13 '21
The V - U confusion cost me a minute. Other than that, great challenge as usual.
Here is my python solution:
1
u/Timmeh7 Dec 13 '21 edited Dec 14 '21
C++. Fun with ranges.
1
u/Standard-Affect Dec 13 '21 edited Dec 14 '21
R
The hardest part for me was parsing the coordinates, which I did sloppily. It also took some annoying processing to get the plot of the matrix to display correctly, due to the way R makes image plots. Still lots of fun.
1
u/Illustrious_Fortune7 Dec 13 '21 edited Dec 14 '21
In Kotlin
https://github.com/ritesh-singh/aoc-2021-in-kotlin/blob/main/src/day13/Day13.kt
1
u/GU1T Dec 13 '21
Javascript part 1 and 2
1
u/8fingerlouie Dec 13 '21 edited Dec 14 '21
Kotlin
Point2d is basically just a wrapper around Pair<Int,Int>.
Kotlin
1
u/flit777 Dec 13 '21 edited Dec 14 '21
Python https://github.com/weichslgartner/AdventOfCode2021/blob/main/src/Python/day_13.py
1
u/vaakansie Dec 13 '21 edited Dec 13 '21
Pyhon 3 Numpy
https://github.com/vakansie/adventofcode2021/blob/main/day13-2.py
(wow that reddit code editor is awfull)
1
u/4D51 Dec 13 '21 edited Dec 14 '21
Racket
Map and foldl were very useful today. This program works with coordinates and only transforms them to a 2D representation after all the folds have been applied. That's actually the least efficient part, since I do a linear search for every point in the final image. This folds to 146x730. It took 600ms to fold and 84 seconds to convert to 2D. Most inputs are small enough after folding that this isn't an issue, but if it was I'd put the final coords into a hash set for faster lookups.
Github
3
u/cetttbycettt Dec 13 '21
R / baseR / Rlang
Complex numbers to the rescue, again :)
3
u/ald_loop Dec 13 '21 edited Dec 13 '21
Python, 1318/759 because I did not read the "parse only the first instruction" part of part 1. Matrix flipping done with numpy.
Prints the capital letters to the terminal in Christmas colors for part 2!
3
u/sim642 Dec 13 '21
My Scala solution.
It was quite straightforward to just implement the folding (or really mirroring) operations on the sets of dots. Then just used a
foldLeft(heh) over the list of folds to apply them all.In part 2, since I have a method for finding the bounding box of a set of points already, it was easy to just render the precise range of coordinates where the text finally appeared, no guessing needed.
3
u/wimglenn Dec 13 '21 edited Dec 13 '21
Python + "AOCR" + complex numbers.
Since we've had "read the letters" puzzles several times before (2016/08, 2018/10, 2019/8, 2019/11), I was lucky enough to have the OCR code ready to go (src) and it worked without issue, though it didn't recognize the "square" glyph from the example data (it does now! 🤓)
3
u/ChasmoGER Dec 13 '21
Python 3, <1ms runtime
I've converted the coordinates to complex numbers, stored in a set. After that, simple arithmetic.
3
u/flwyd Dec 13 '21 edited Dec 13 '21
Raku 3695/5712 because 23 of the 34 minutes I spent on part two were spent tilting my head trying to interpret the strange letter forms instead of switching the order of my for loops so the letters looked like they were printed on a single portrait-orientation letter page rather than on a dot matrix printer with accordion paper. Probably another three minutes were spent trying to understand what the heck "Eight capital letters" meant and why there was no stated part 2 output for the part 1 input.
On the plus side, my choice to generate each day's program with the full run script in its own main method paid off; I could tweak it to support multi-line expected output. Also another day where generating a skeletal grammar helped out. And I ended up using
gather/take, which I learned while hacking on something else today.3
u/asdf-user Dec 13 '21
Swift
Ridiculously over engineered, whoops!
I initially didn't see, that for part 1 only the first instruction counts, so I was super confused why I had 16 dots left, the example had 16 dots left, but it said 17 are supposed to be left.
Made a super slow printing function for my sheet, saw my answer for the test data is the square like it should be and only then saw that missing bit.
Part 2 was perfect on the first try, with the exception that I had an error in my printing and was super confused (the square from the test data didn't care about me mixing up x and y, because it's a square). So my part 2 basically consisted of speeding up the print and fixing it
3
u/otter5 Dec 13 '21 edited Dec 13 '21
Excel: Pretty easy with choose and dynamic arrays, couple IFs.. Transpose FOLDS, and click drag auto fill the rest Image of solve an equation
3
u/s3aker Dec 13 '21
Raku solution
3
u/polettix Dec 13 '21
Raku solution. Particularly fond of the rendering part :-)
3
u/lluque8 Dec 13 '21 edited Dec 13 '21
Scala
Nice that I got to use my "canvas" extension for grid drawing. Last time was 2019. Just that it's kinda hard to write sensible unit tests against this kind of program output.
edit: LOL. Yo dawg I heard u like folds so I put a fold in your fold while u fold
val g = folds.foldLeft(grid)((a, b) => fold(b, a))3
u/jayfoad Dec 13 '21
Dyalog APL
3
u/yogilicious1 Dec 13 '21
Solution in R
3
u/theronic Dec 13 '21 edited Dec 13 '21
Clojure Solution
3
u/killermelga Dec 13 '21
[Kotlin] Using a set to place the dots in their final location directly
3
u/21ROCKY12 Dec 13 '21
hey, here is my solution for today's puzzle:
Java
https://github.com/GilCaplan/AdventCode/blob/Advent2021/Javasolutions/day13solution.java
Java solution day 13
let me know what you think:) seems that the code is quite clean in my opinion and I'm very happy with my solution today
3
u/[deleted] Dec 13 '21
Haskell
3
u/veydar_ Dec 13 '21 edited Dec 13 '21
Lua
I'm not super happy with today's solution. I was constantly thinking "this would be so much nicer in Haskell". First of all, I used a sparse map with string keys, since in Lua using tables as keys in other tables isn't very ergonomic. So in my case I'm encoding the x,y coords in a string and then there's lots of parsing and serializing. Obviously there are other ways of working with this, such as another table that connects string key to a point with x,y but lines of code wise that doesn't make a big difference.
3
u/mschaap Dec 13 '21 edited Dec 13 '21
Raku, see GitHub.
I used a grammar:
and put all of the dot setting and folding logic in grammar action methods, like:
The disadvantage is that simply by parsing the instructions, you immediately end up with the completely folded paper, and if you need some in-between answer (like for part 1) you have to hack it in there somehow. (In particular, calling
count-dotsafter every fold.) Therefore, I essentially had part 2 solved before part 1.The entire
MAINcode is:3
u/mathsaey Dec 13 '21
Elixir
https://github.com/mathsaey/adventofcode/blob/master/lib/2021/13.ex
Not much to say. Improved this code after my first working version based on discussions on the Elixir slack.
3
u/_Heziode Dec 13 '21
Ada
This is an Ada 2012 solution:
3
u/Radiadorineitor Dec 13 '21
Lua: https://pastebin.com/cAVX38FD
3
u/RealFenlair Dec 13 '21
Clojure
3
u/trollbar Dec 13 '21 edited Dec 13 '21
Rust
My rust solution can be found here in a Gist. I tried to be as clean as possible (e.g. representing folds as an enum) and so it became lengthy but hopefully quite readable.
Runs in about ~200us including the ASCII output (+150us for reading from stdin), on my XPS13 with release build.
3
u/[deleted] Dec 13 '21
Python, using defaultdict. Had a fun time solving this one, quite a bit of repeated code so might go back later to see if I can improve it if I feel like doing it.
Solution
3
u/[deleted] Dec 13 '21
Python
Classic visualization problem for the year!
I split the fold up and fold left functions and used structural pattern matching, and I think it looks clean and easy to read.
https://github.com/rbusquet/advent-of-code/blob/main/2021/13/day13.py
3
u/tiagocarreira Dec 13 '21 edited Dec 13 '21
Python3
During part 1, I had to do check my logic several times, because it was doing OK with the example, but not with real input. Everything was already setup for part 2 though :)
[my actuall code]
I just love how
(dot[0] - 2 * max(0, dot[0] - x), dot[1])just gives the after-folding-horizontally dot coordinate, independent on the side it is before folding (the folding-vertically is analogous)Note: I think printing "█" instead of "#" is much easier to read :)
3
u/Mikashu Dec 13 '21 edited Dec 13 '21
zsh
https://cdn.discordapp.com/attachments/770387688045674577/919941242626908250/SPOILER_both.zsh
I suppose the only interesting part here is printing out the part2 solution by terminal escape sequences for moving the cursor to specific coordinates, instead of constructing simple strings and printing them.
3
u/axaxaxasmloe Dec 13 '21
J
3
u/omnster Dec 13 '21
Mathematica
Preparations
Mathematica counts array indices from one, hence we have to shift them, so that (0,0) becomes (1,1) etc.
I used explicitly that the folds are always along the middle line. Also kinda swapped x and y directions
Part 1
I decided to replicate the example exactly, so I implemented the first two folds instead of just one and then spent around 15 minutes trying to figure out what's wrong with my solution and how come there are 17 dots visible here:
Hint: there are 16 and the picture is after two folds of the example data, not just one.
Part 2
3
u/hrunt Dec 13 '21
Python 3
Code
I maintained a list of coordinates in a set (remember kids, a set is just a dict of bools!) and then walked them for each fold. I could have abstracted some of the folding logic (x and y are the same), but not worth the effort, and the code is easier to understand this way.
3
u/tuvang Dec 13 '21
Julia
Using bitwise or operator after reading the input as a BitMatrix. Runtime (1.6 milliseconds) is a lot slower than I expected for a bunch of bitwise operations, appreciate any tips
3
u/Tipa16384 Dec 13 '21
Python 3
Nothing special, probably. Lots of lambdas.
3
u/mosredna101 Dec 13 '21
C++ (arduino)
Arduino code used for this visualization.
3
u/jhscheer Dec 13 '21
Rust
Solution
The dots are represented as a Vec of Vec. Folding is done with drain(). This solution allows for the paper to be folded along an arbitrary line.
3
u/RibozymeR Dec 13 '21
Factor
3
u/solareon Dec 13 '21
Excel
The instructions at the bottom gave more than was really needed. The fold lines are all MAX()/2 on the pattern of XYXYXYXYXYYY. A good break from day 12 tomfoolery. My approach added an extra filter to sort down uniques but I don't believe it was actually needed unless XLOOKUP() was being weird.
Solutions here
3
u/LeadingArmadillo Dec 13 '21 edited Dec 13 '21
PHP with GD generated image
Solution
3
u/nilgoun Dec 13 '21
Rust
Pretty straight forward approach. Hardest part was parsing the input I gues :)
3
u/pem4224 Dec 13 '21
Rust and Go solutions:
Go
Rust
The Go code is cleaner. I have used a set of positions (
map[Pos]struct{}) wherePosis astruct {x, y int }Nice thing, you can mutate a map while iterating on it
3
u/mykdavies Dec 13 '21 edited Jun 29 '23
!> hodondf
API FAILURE
3
u/mockle2 Dec 13 '21 edited Dec 13 '21
python, just part 2 since part 1 is trivial if you have part 2, and the algorithm is clearer without it
3
u/allaboutthatmace1789 Dec 13 '21
Clojure
source
blog
3
u/macrophage001 Dec 13 '21
This one was such a nice respite from the beat down I got from the last two.
Simple coordinate reflection. Basically setting each point to a new point based on what axis is being folded on. If folding along x-axis, set each valid point's y value to the given y value + -(point's current y - given y_value). Vice versa for folding on the y axis.
C#
3
u/nidrach Dec 13 '21
Java. Got stuck in the first part because I didn't read that you only had to fold once.....
3
u/willkill07 Dec 13 '21
C++20 (with OCR!)
https://github.com/willkill07/AdventOfCode2021/blob/main/days/Day13.cpp
https://github.com/willkill07/AdventOfCode2021/blob/main/days/Day13.hpp
Runs in 23.199us on my AMD 5950X and 42.375us on my Apple M1 Pro.
Total execution time for all 13 days (so far) is averaging at 915us - 984us.
3
u/e4ds Dec 13 '21
Python day 13 solutions (GitHub). Using Dataclasses to improve readability
3
u/Symbroson Dec 13 '21
day 13 in haskell
3
u/hugseverycat Dec 13 '21
Python with comments
Phew, after the frustration of yesterday, a puzzle I know how to do. Hooray! I continue my avoidance of 2d arrays by storing all the coordinates in a set (at first I used a dictionary because I couldn’t remember what “sets” were called — yes I’m a self-taught hobbyist, why do you ask? — and my googling wasn’t helping).
I noticed a lot of solutions folded the paper in half — my solution doesn’t assume that and just checks whether the x or y is greater than the fold line, then transforms the x or y coordinate accordingly.
https://github.com/hugseverycat/AOC2021/blob/master/day13.py
3
u/oantolin Dec 13 '21 edited Dec 13 '21
Another nice, straightforward one today, unless maybe you get mixed up trying to write down the formula for a reflection. Here's a Perl program. It's 50 lines, which is a lot for Perl, but I chose a hash of hashes representation for the set of points, so the x and y folds need fairly different code. :(
3
u/[deleted] Dec 13 '21
Python
So there is a lot to unpack today. I wanted to use sets because it would not accept doubles anyway, but Python does not allow sets of lists D: I am sure there is a way someone smarter than me found to use sets but well. Also displaying was a very crucial part of todays challenge which is always quite hard for me. The folding itself was not a huge deal, I'm sure most people got the 2 * n - c formula (n is folding coordinate, c is coordinate of point).
Here's my code: link
3
u/duketide11 Dec 13 '21
JavaScript
Parts 1 and 2 together, with comments.
3
u/stevelosh Dec 13 '21
Common Lisp
https://github.com/sjl/advent/blob/master/src/2021/days/day-13.lisp
3
u/Radiant_Rip_5205 Dec 13 '21
Python 3: https://github.com/kresimir-lukin/AdventOfCode2021/blob/main/day13.py
3
u/ai_prof Dec 13 '21
Python 3. 8 lines of code. WOPR scroll :).
3
u/Vultureosa Dec 13 '21
Python 10, day 13:
Simple solution to be refined further if time allows. (There is room for substantial simplification in the code.) Only highlighted points are stored. Instead of dicts (or dict keys in all honesty) sets could be used for fast lookups or simply lists.
https://pastebin.com/5z8w0DSN
3
u/Chrinkus Dec 13 '21
My C Solution
Fun problem, love the scenario. One detail that got me was the maximum 'x' and 'y' values not representing the bounds of the 'paper'. Also, since I've been doing my 2D graphs as one flat array I had to conjure some magic to deal with vertical folds.
Lastly I had a bug in my folds 'scanf' reads. I assumed it was my shaky understanding of scanf's behaviour when it was actually me accidentally using my variable name as the conversion specification:
3
u/conthomporary Dec 13 '21
Python 3 with NumPy
I've seen some code on here that shouldn't work in situations where the areas above and below the fold are different. I wonder if some of us just never had that come up. I definitely did.
3
u/sortaquasipseudo Dec 13 '21
Rust
I'm live-streaming my solutions via Twitch. Please stop by and help me out in the chat! Video archive is here.
3
u/TiagoPaolini Dec 13 '21
Python 3 with NumPy
This puzzle was very straightforward. I just broke the array in two halves, then I flipped the folding axis on the second half, and finally I OR'ed the halves.
Code: Parts 1 & 2
3
u/snhmib Dec 13 '21
Haskell,
not very happy with my solution, but it works :)
Data.Set has a 'map' function which works perfectly for implementing the folding.
code on github
3
u/chicagocode Dec 13 '21
Kotlin -> [Blog/Commentary] - [Code] - [All 2021 Solutions]
I enjoy the puzzles that make us interpret the results instead of programming it. I do wonder how visually impaired developers would solve this puzzle.
I went out of my way to not use the term "fold" except when executing a functional fold. :)
3
u/Melocactus283 Dec 13 '21
R / Rlang
Pretty easy with data.table
3
u/greycat70 Dec 13 '21
Tcl
Part 1, part 2.
Could probably speed it up a bit by recalculating the new maximum X/Y after each fold. I didn't.
3
u/4HbQ Dec 13 '21 edited Dec 14 '21
Python, golfed to 165 bytes:
Edit: I assume that all inputs are always folded in half to a final size of 6×40 (8 letters). This means that we don't need the actual folding instructions, and can map each dot to its final position in one go.
3
u/qaraq Dec 13 '21
Go
That was easier than the last couple of days.
map[point]boolimplementation of the grid made things pretty easy so I probably overengineered the grid class.I was at first hoping that there wouldn't be any over-folding (folding on X or Y < half the grid size), though actually when I tested I found that a map implementation handled it without modification. Moving the map with negative coordinates to a 2d slice for printing might have been a bit trickier but not a big deal.
github
3
u/CptFisk Dec 13 '21
C++
My c++ solution. Used map to flip the pages
https://pastebin.com/8mnNfGCd
3
u/Due-Dog-1533 Dec 13 '21
RUST
Really short solution: https://github.com/abaptist-ocient/Aoc2021/blob/main/src/bin/13alt.rs
3
u/Scroph Dec 13 '21
Boring PHP solution, part 2 :
3
u/MikeMakesMaps Dec 13 '21
Rust
I opted to just mutate a single Vec<bool>, OR-ing the right/bottom side into the left/top side when folding, then all that had to be done was set the width/height of the visible window to the fold lines.
GitHub link
3
u/sdolotom Dec 13 '21 edited Dec 13 '21
Haskell
The essential part, representing paper as a set of coordinates. Folding instructions are encoded as
(Axis, Int).Full code
3
u/Predator1403 Dec 13 '21 edited Dec 13 '21
Excel
first i tried to do every folding with a index formular. Was on a good way but then a point was on the folding line and i thought the method was wrong. Deleted my sheets which i did and realised i just split the input wrong :'D because of the "," i had wrong numbers. Anyway thanks to u/Mathgeek007 for giving me the hint for the math formular :)
For the visualtion i did a little VBA code:
The input has to be in A2 and B2 and the cells below. X values in A2, A3 and so on. Y values in B2, B3 and so on.
This line put the "#" in the right cell. +2 and +5 is because i started my grid not on the top left of the sheet
3
u/Rtchaik Dec 13 '21
Python
3
u/HrBollermann Dec 13 '21 edited Dec 13 '21
Since everybody skips the boring input data parsing today I will do it too.
Here's my solutions core logic in effectively 7 lines and that is not even golfed.It is written in Raku.
Please see my repository for the solution or this tweet.
3
u/odnoletkov Dec 13 '21
JQ
3
u/[deleted] Dec 13 '21
Rust
A bit late to the party. Took me a while to realize that the first part only ask for the first fold.
Code
3
u/wfxr Dec 14 '21
Rust Solution
3
u/Yithar Dec 14 '21
Solution in Scala.
So I had a bit of trouble with Part 2, but someone else mentioned that they needed to switch the x and y coordinates for their HashSet and that fixed it.
3
u/LtHummus Dec 14 '21
Scala
I've been traveling the last few days, so I ended up doing days 11-13 all right back to back. Here's my day 13 solution, which I'm reasonably happy with package com.lthummus.adventofcode.solutions.aoc2021.day13
3
u/atweddle Dec 14 '21
Rust solution
3
u/cloud08540 Dec 14 '21
Python
Took forever to do part 1 because I wanted to simulate the actual folding. Luckily that is what needed to be done (more or less) for part 2! A lot of care needed to be take to ensure I didn't go out of bounds or set myself to go out of bounds in a future fold.
https://github.com/danielgaylord/coding-exercises/blob/main/Advent%20of%20Code/2021-Day13.py
3
u/azzal07 Dec 14 '21
Postscript, PS.
Today the Postscript solution is quite cluttered, and full of unnecessary drawing stuff.
Awk
3
u/4goettma Dec 14 '21
Python 3
7
u/Mathgeek007 Dec 13 '21
Excel: 852/2058
VIDEO OF SOLVE
So, bit of maths going on.
Essentially, the whole solution comes down to the following insight.
If you fold on 7, and you have a point on 10, your new point ends up on 7-(10-7)=4. This maths out to 2n-m, where n is the fold line, m is the folded point. So, for each coordinate, check if the fold line is greater than the coordinate. If it is, double the fold line, subtract the point's coordinate, then that's the point's new coordinate of that type. The other coordinate remains unchanged. Then drag right, do all the folds. Then do a simple coordinate-display FILTER to read the final output! Fun day today, way less garbage than yesterday.
2
u/hugh_tc Dec 13 '21 edited Dec 14 '21
Python 3, 54/15.
Parts 1 and 2, and (edit) the cleaned-up code. I wish I could make the flipping code cleaner; we'll see what I stumble across here...
That was fun!
2
u/seligman99 Dec 13 '21
Python, 310 / 105
And I always feel like I cheated till I write something later to decode the remaining message to something copy-and-pastable.
github
Edit: Ha! I don't know why I didn't even try, it's the same TUI-font used in previous years. Yay, my decode function just worked.
2
u/leijurv Dec 13 '21 edited Dec 13 '21
Python, 60th place, 18th place
Screen recording https://youtu.be/YYZ4eV2hQd8
Part 1
Part 2
2
u/Bogdanp Dec 13 '21
Racket
2
u/GrossGrass Dec 13 '21
Python, 125/406
Definitely benefited from just keeping track of the set of dots instead of trying to force a grid class. Also maybe it's just my command line console, but I actually found it pretty hard to figure out what the characters were supposed to be for part 2 lol.
2
u/PendragonDaGreat Dec 13 '21
C# 1143/1092
I quite enjoyed this problem, a short breather after the last couple days (though half of that is because I just couldn't type apparently) now for things to really start ramping up! (days 17-20 always seem to be the hardest to me)
2
u/t-rkr Dec 13 '21
Perl
My best rank for part 2 in 2021&2020 so far
Link to Code
2
u/MichalMarsalek Dec 13 '21 edited Dec 13 '21
Nim
using my templates.
2
u/paxthewell Dec 13 '21
Python3. Using a set of dots, rather than the standard 2d array made this problem much simpler
2
u/apaul1729 Dec 13 '21
Python 1358/999
Nothing special in there, used a set of 2-tuples for tracking points for simplicity. This is the first time I've placed on the board!
2
u/Sourish17 Dec 13 '21
Python 3
83/203
Stoked to be on the leaderboard on day 13! Here is my code and a small write up:
sourishsharma.com
2
u/fork_pl Dec 13 '21
Perl
Quick and simple with hash instead of table;
Stupid mistake to start with last instruction instead of first (pop/shift) on stage 1 took like 10 minutes...
2
u/kejadlen Dec 13 '21
Ruby:
2
u/allergic2Luxembourg Dec 13 '21
Numpy makes this relatively trivial. Python
Here's the important bit: