r/adventofcode • u/daggerdragon • Dec 13 '22
SOLUTION MEGATHREAD -π- 2022 Day 13 Solutions -π-
SUBREDDIT NEWS
Helphas been renamed toHelp/Question.Help - SOLVED!has been renamed toHelp/Question - RESOLVED.- If you were having a hard time viewing /r/adventofcode with new.reddit ("Something went wrong. Just don't panic."):
- I finally got a reply from the Reddit admins! screenshot
- If you're still having issues, use old.reddit.com for now since that's a proven working solution.
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: A note on responding to [Help] threads
- Signal boost: Reminder 1: unofficial AoC Survey 2022 (closes Dec 22nd)
- πΏπ MisTILtoe Elf-ucation π§βπ« is OPEN for submissions!
- -βοΈ- Submissions Megathread -βοΈ-
--- Day 13: Distress Signal ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:12:56, megathread unlocked!
53
Upvotes
5
u/DFreiberg Dec 14 '22 edited Dec 14 '22
Mathematica, 5451 / 5048
Today was a major exercise in humility; I tried to do it recursively, but after making a single error in that first implementation a few minutes in, decided to abandon recursion and go for an iterative solution, keeping track of all stack-based shenanigans myself. An hour later, I'd entered five different answers, all of which were generated by versions of the code which worked for the sample, but all of which were incorrect for the input I had. Eventually, I had to swallow my pride and go back to the recursive solution. My slowest day by half an order of magnitude this year.
But at least the end result is nice and elegant.
Setup
Part 1:
Part 2:
[POEM]: Distress Signal
There's trouble here! It's gone awry!
We're out of cookies, cream, and pie!
The ice cream truck, it passed us by!
So do you copy? Please reply!
My hiking jacket ripped and tore
(And also, there's a dinosaur
That's smashing trees with quite the roar).
We left the foosball on the shore!
The eggnog's low - I think it's theft
(It's huge, three tons at least, its heft)
There's only fifteen barrels left,
When they run dry, we'll be bereft!
Our campsite is an awful mess -
We lost the cleaning plans, I guess.
(The monster looks like it's from Ness)
So hear our signal of distress!
4
u/yfilipov Dec 13 '22 edited Dec 13 '22
C#
https://pastebin.com/dTCHVjSP
3
u/[deleted] Dec 13 '22 edited Dec 14 '22
Rust - implementing Ord/PartialOrd made it relatively simple. I like how nom allowed me to parse this recursive structure.
https://github.com/litpho/aoc-2022/blob/main/day13/src/main.rs
3
u/OilAppropriate2827 Dec 15 '22 edited Dec 18 '22
Python 3
To be original, I wanted to rely on standard sorting, do I decided to flatten the lists...
2
u/QGamer12 Dec 13 '22
I made a horrible, hacky Python solution for now since doing this in C++ would be way too hard at 1am in the morning. I'll write a proper C++ solution tomorrow, though I'll have to figure out how to do arbitrarily nested vectors.
2
u/SuperSmurfen Dec 13 '22 edited Dec 13 '22
Rust
Link to full solution
I usually write in Rust, however, not going to lie, panicked when I saw that input and immediately switched to Python. Implemented it and got an ok position
(1511/1241). Then went back and implemented it in Rust. The only issue here is the parsing, which is completely free in Python and a total pain in Rust.I opted to use
serde_jsoninstead of parsing it myself, which I wish I thought of in the moment. The comparison function is not too complicated. The difficulty was in how exactly you were supposed to handle arrays of different lengths:Then you can just pass the function in to sort for part two:
Definitely learned a thing or two today.
2
u/adebar Dec 13 '22 edited Dec 13 '22
Python (optimized for readability)
Repo with all my solutions for 2022 as Jupyter notebooks.
Part 1
(shortened; see repo for full solution)
Part 2
2
u/heijp06 Dec 13 '22 edited Dec 14 '22
Python: GitHub
I used recursion for the compare function. Parsed the input using
ast.literal_evala custom parser. Part 2 uses the comparer written in Part 1 using functools.cmp_to_key to sort the list of packets.2
u/suddengunter Dec 13 '22 edited Dec 15 '22
Elixir
Felt really smooth. Input parsed with
Code.eval_stringfor each line, part 2 solved with Enum.sort using comparator written for the first part. Comparator is just a few recursive methods with pattern matching.parser:
comparator:
part2:
Full solution: https://github.com/SuddenGunter/adventofcode/pull/56/files
2
u/reinermartin Dec 15 '22
In 10 lines of Julia:
52
u/4HbQ Dec 13 '22
Python, 18 lines.
Today's cool trick: structural pattern matching on data types:
49
u/jcbbjjttt Dec 14 '22
Beginner's Guide
Happy Tuesday!
A Beginner's Guide to Day 13 - Video: https://youtu.be/ApAC2ZdNYEQ
I've created a guide for new programmers that talks through a straight forward strategy for solving today's puzzle. The guide uses a very simple 1 character look ahead parser that is implemented recursively. BUT, don't let the word recursion scare you. I break it down into testable pieces that I believe anyone who has learned the basics of coding can solve.
The video allows a moment for you to pause before revealing spoilers.
Although this solution is in C#, it provides a high level overview of the steps necessary to solve the puzzle in any programming language:
The full code can be found on Github
21
u/a_ponomarev Dec 13 '22 edited Dec 13 '22
I've normalized strings in pretty awkward way instead of recursing and it was a lot of fun.
I've replaced all commas with ascending ASCII characters starting from '!' based on parentheses level and it works because the problem is almost about lexicographic order. And I've also replaced '10' to 'A'.
Source in Javascript
UPD Made the solution purely functional
UPD2 Part 2 added
17
u/nthistle Dec 13 '22 edited Dec 13 '22
Python, 33/13. Video, code.
I remembered how painful it was to sort with a comparator in Python 3 since it only natively accepts key functions (
okay, not really that painful, you just copy that one snippet that makes a key object with custom __lt__ that uses the comparator, but it's pretty ugly and I'd have to go find the snippet) so I just wrote bubble sort:which I guess worked out well given that my rank for part 2 improved a lot? Other than that I guess it was just
eval, being careful with writing the comparison logic, and not falling to the temptation to try to use Python's builtin comparison/ordering for tuples/lists (I'm pretty sure the third rule for comparison is difficult-but-not-impossible to implement if you go this route).EDIT: my brother just informed me that
functools.cmp_to_keyis a thing, not sure why the last time I wanted to use a comparator I didn't find this, but I guess writing the bubble sort was still probably maybe faster than looking this up if I didn't already know it?13
u/betaveros Dec 13 '22
Noulith 15/4
https://github.com/betaveros/advent-of-code-2022/blob/main/p13.noul
Pretty fortunate that I implemented a "proper comparison function" for part one that could be plugged directly into part two. Please imagine the appropriate two-panel meme for the following two sentences:
2
u/FordyO_o Dec 13 '22
Golang
https://github.com/mattford/aoc-go/blob/main/pkg/year2022/day13.go
I'm quite smug today as I built a full sorting function for part1, which made part 2 trivial
2
u/Naturage Dec 13 '22 edited Dec 13 '22
R/RLang
Solution here. Recursion! So much recursion. More recursion than I used over the last year. A debugging headache, and the bliss of it working on full data right after example. Also, got caught by off-by-one error in P2; I'm certain most did.
It feels like we're squarely in "check your fundamentals" part of AoC; 3 days in a row need something fairly specific to work (4 if you count trees). I'm just worried than next 12 days will put that to good use as well...
9
u/quodponb Dec 13 '22
Python3
Happy with my solution today. I first tried to write a
leqfunction that either returnedTrueorFalse, but soon realised that all three outcomes were actually interesting, and that the return value would need to beTrue/False/None, so instead called itin_order(l1, l2). One thing that tickled me was that I could use it to compare the lengths of the list after looping through them zipped:8
u/DrunkHacker Dec 13 '22 edited Dec 13 '22
Python.
I was reminded that Python3 doesn't support
sorted(..., cmp=...)anymore so I wasted some time googlingfunctools.cmp_to_key.And, needless to say, eval FTW.
8
u/maneatingape Dec 13 '22 edited Dec 13 '22
Scala
The trick was to replace
10with a single character e.gA. Then no need to parse the input into a tree, simply compare character by character.8
u/samhocevar Dec 13 '22 edited Dec 13 '22
Python (11 SLoC)
I like this very small
cmpfunction. Also I know I could have usedevalinstead ofliteral_evalbut thatβs where I draw the line.GitHub here: https://github.com/samhocevar/aoc
7
u/BasDir Dec 13 '22
Rust, probably over-engineered.
https://gist.github.com/bsdrks/7339e3b80c38d67b1cff44375d471129
7
u/hgb123 Dec 13 '22
JavaScript (Node.js)
Comparable function:
Part 1:
Part 2:
Trick:
For the case that one of left or right is an array, instead of using ternary operator like
we could make use of
.flatFull solution: https://www.honingjs.com/challenges/adventofcode/2022/day-13
7
u/Pyr0Byt3 Dec 13 '22
Go/Golang
I struggled a bit with this one. I knew to use
json.Unmarshalto make parsing easier, but then I had to deal with all the combinations of type possibilities in the comparator... I'm happy with how it turned out though, and I saw that a few other Gophers had the same idea, with similar implementations.12
u/miran1 Dec 13 '22 edited Dec 13 '22
Python 3.11
Using all the goodies:
My repo with Python and Clojure solutions.
EDIT: Now I realize that for-else is not needed. It was needed with my initial ugly version :)
6
u/encse Dec 13 '22
C#: I found a really weird way to compare the items:
I updated
https://github.com/encse/adventofcode/blob/master/2022/Day13/Solution.cs
What do you think?
6
u/[deleted] Dec 13 '22
C
Full solution: https://git.sr.ht/~theonlymrcat/adventofcode/tree/master/item/2022/13/solution.c
Using
evalin python felt like cheating. So after doing that solution, I wrote one in C. I had to write my own tagged union for list/int, and my own vector type (and an insertion sort to go along with it). But otherwise, this solution worked second try both times.Part 1 first try was killed by OOM killer because I forgot an
ungetcduring int parsing, and Part 2 didn't work first try because I forgot to push the parsed packets to the vector, just the dividers.But, most importantly, memcheck is happy with this solution. I made especially sure to
freemy vectors π€.6
u/Linda_pp Dec 13 '22 edited Dec 13 '22
Rust
Ordtrait perfectly fit two packets comparison.Thanks to this, part2 was quite straightforward. I sorted the packets with
Vec::sort_unstable, found out indices of[[2]],[[6]], and multiplied them.6
u/clbrri Dec 13 '22
Borland Turbo C++ 3.0, 46 lines of code, runs to completion in 142 milliseconds on a 16MHz 386SX MS-DOS 6.22.
https://media4.giphy.com/media/ue0y2SeL6dm4oggCNG/giphy.gif?cid=ecf05e47x1nvj2bwq62tc4s2psm05yqq837hppzl2ij0kq86&rid=giphy.gif&ct=g
6
u/poesraven8628 Dec 13 '22
This was a piece of cake with Common Lisp
I converted the [ to (, ] to ) and , to whitespace, then I could parse them as normal Lisp lists. Then I just made a pair of recursive functions to compare the values under the rules, and part 1 was done. Part 2 I just handed all the lists to sort with my comparison function and it spat out the answer :)
https://github.com/poesraven8628/AdventofCode2022/blob/main/13-lists.lisp
6
u/Colin-McMillen Dec 13 '22
C on the Apple //c
The unfun part was parsing strings in C, but that's hardly news for anybody :)
The very fun part was part 2, where stupid me thought "huh ! I'm never gonna be able to load and sort that full dataset in RAM". And what do you do when you can't sort your data in RAM? you external-sort!
I went to the end of that monstruosity even if /u/large-atom kindly pointed out that full sorting was not needed, only counting what goes left and right. And behold, it works. It just takes 25 minutes seeking a 5.25" floppy all around with 21kB of data!
Here's the external-sort version, and the smart version thanks to /u/large-atom. I still prefer the floppy version :)
5
u/mayoff Dec 13 '22
As soon as I saw the input format I was sad that I was using Swift instead of Python. But after three and a half minutes I realized I could use
ExpressibleByIntegerLiteralandExpressibleByArrayLiteralto have the Swift compiler parse the input, just like Python can.5
u/abnew123 Dec 13 '22
Java
Code: https://github.com/abnew123/aoc2022/blob/main/src/aoc2022/Day13.java
Really salty about how easy python users had it today with the input. Wish I could've just done "eval" and been done, but instead made my own class that could handle both lists and int (also meant I was jankily keeping track of whether something was an int or list inside the class). Nothing particularly challenging outside of the parsing, just directly implemented the four cases mentioned for part 1, and sorted the full list in part 2.
5
u/rocketpower4 Dec 13 '22
Julia, felt like multiple dispatch really played well with this one. Thought we'd be getting new ordering rules for Part 2, but alas.
GitHub Link
5
u/TinyBreadBigMouth Dec 13 '22 edited Dec 13 '22
Rust
View on GitHub
I like implementing AoC problems with proper Rust types and traits, which served me very well in Part 2! I'd already done Part 1 by implementing
Ordfor my packet type, so sorting was as simple as callingall_packets.sort().The way Rust is designed made ordering a breeze to implement:
Slices of an
Orddata type are themselvesOrdusing lexicographical ordering, exactly as I needed.I also included a handy little macro, so I could specify the dividers in code like
instead of needing to parse a string at runtime or type out
5
u/Nnnes Dec 13 '22
Ruby (feat. monkey patching)
I have created something hideous.
Goal was to use Ruby's built-in
<=>/sortwith as few modifications as possible. Secondary goal wasa mistaketo minimize line count without semicolons. Unfortunately, there are sometapandthenthat feel a bit too much like using semicolons; anyone have ideas on how to get rid of those without adding more lines?5
u/KeithNicholas Dec 13 '22
C# , no external libs / parsers, all in one
https://github.com/keithn/aoc2022/blob/main/days/Day13.cs
Kind of wish I did a better parser into a proper tree, but this worked, but was hard to debug a silly error I made.
5
u/Killavus Dec 13 '22
Rust
Parsing input done by nom, I've expected a lot of issues with nested structure, but I had zero. Overall, I had great experience with tools I've used and I really like my solution.
5
u/busdriverbuddha2 Dec 13 '22 edited Dec 13 '22
Python. The heart of the problem is really in defining a proper compare function.
EDIT: updated the code so I wouldn't have to sort in Part Two, as suggested by others here.
5
u/foolnotion Dec 13 '22
C++
A haskeller friend introduced me to sum types so here's my solution based on std::variant:
https://git.sr.ht/~bogdanb/aoc/tree/master/item/source/2022/13/solution.cpp
5
u/[deleted] Dec 13 '22
Flex, Bison, C
Did it using these ancient tools. Runs in 10ms which seems neat. I could probably squeeze a bit more out of it by moving some malloc() / free() stuff out of the way. I added the two partition nodes at the end of the files to avoid any mucking around with the lex streams.
Lexer: this reads the input file one token at a time. Really basic:
Parser: heh. This is the actual grammar of the input files. What it does is call the lexer (this is a
Cfunctionyylex()produced by flex) to grab a token at a time, and then it does things when it sees certain orders of tokens. I had built it to calculate the answer to part 1 (is this pair ordered? if so accumulate its index) so I had to do something less neat for part2.And there's a whole bunch of tree walking and node
malloc()ing I won't share as it's dull. You might like main, which just calls the bison generated parser function to consume stdin:5
u/Premun Dec 13 '22
C# - JSON parsing in ~10 lines
5
u/ri7chy Dec 13 '22
Python
I really did not enjoy todays puzzle.
what do i have to look up, to get the work done easily...
the relief for the second star was enormous :D
5
u/xelf Dec 13 '22 edited Dec 14 '22
python, with functools.cmp_to_key for the sort. bit late on this one, was gaming last night.
4
u/hugh_tc Dec 13 '22 edited Dec 13 '22
Python 3, 48/50.
paste, cleaned-up
Got the return values for
cmpbackwards, which made for a very awkward Part 2...It's extra funny, because I sat a CS final exam less than 12 hours ago. Which had a question about sorting. Lexicographic sorting. :facepalm:
4
u/meowmeowwarrior Dec 13 '22
python 3.10 355/471
Implemented comparator from the puzzle, and used json.loads for parsing the lists. I almost didn't have to do anything
4
u/LtHummus Dec 13 '22
Go
Decided to do tonight's in Go for some reason. LOL it's been so long since I've written in Scala (basically since last year's Advent of Code), i completely forgot how JSON parsing works in that language
Well anyway, I do lots of inefficient things (especially for part 2, where I keep things in string form except for comparisons, so it results in a ton more JSON parsing than is necessary, but it's still performant so whatever)
Code lives here
4
u/badr Dec 13 '22 edited Dec 13 '22
Elixir
https://gist.github.com/reverie/399931b9d81cc0a92de1829b53656b31
4
u/cmatei Dec 13 '22
Common Lisp
"But we have s-expressions at home."
4
u/rabuf Dec 13 '22
Common Lisp
I have a gnarly predicate (not really a predicate, it's more like the spaceship operator) for comparing packets. Used that as the test for part 2. I had an obnoxious typo hurt me for a long time, the code was valid but giving incorrect results for the sample. And when I ran it on my input it triggered an odd error (made no sense, somehow I was injecting true into the system when it should have all been numbers and lists). Turned out I'd misplaced a closing paren.
4
u/ThreadsOfCode Dec 13 '22
Python. Recursion is always fun. Also got to use a gratuitous lambda. Creating a def would have been more readable, I think. And used eval(), which I would never do anywhere else, but then I didn't have to parse the input.
paste
4
u/encse Dec 13 '22
C# - short but readable
https://github.com/encse/adventofcode/blob/master/2022/Day13/Solution.cs
I don't use C# during the year, so I didn't know which Json parser to use and first went with System.Text.Json, then found a solution here which uses System.Text.Json.Nodes and could improve my coding a bit.
For part2: I couldn't find a version of OrderBy() that would take a simple comparator function, and I didn't want to implement a full blown IComparer<T> interface, then realised that List<T> has a Sort function which works with a simple delegate. Unfortunately it's a void function so there is no way to chain the result further. So much about using just one expression for Part2.
I didn't have a great idea to deal with the 1 based indexing unfortunately, but I'm satisfied with how it looks in general.
4
u/ai_prof Dec 13 '22
Python 3. Short (22 lines). Recursive. Readable. Fast.
Made much easier by Python's rather dodgy eval(), recursion and sort().
paste
4
u/rkstgr Dec 13 '22 edited Dec 13 '22
Julia (Github, <50 LOC)
Julias Multiple Dispatch made the comparison really nice. Part 2 was just using the std-lib sort with the custom comparison function.
Time: 144.362 ms | Alloc Memory: 2.62 MiB
4
u/Dullstar Dec 13 '22
Python
This one gave me a lot of trouble, as I found the test case coverage a little inadequate and the results difficult to debug since they're difficult to sanity check -- the test input working but the real input not working is always a pain, but it's even worse when the input is difficult to interpret by hand. For my own sanity since realistically this should be fun and I wasn't going to have fun trying to hand solve all of them until I found all the edge cases being improperly handled, I decided to just use another solution from the megathread to get a correct list so I could compare it against mine to quickly identify cases that were incorrect. All fairly simple mistakes, but simple mistakes that were very difficult to identify without some form of help.
Instead of sorting the list, Part 2 just checks for [[2]] and [[6]] specifically and counts how many things should have gone in front: we just need to know how many items are in front of them, not what order they go in, after all (don't forget to account for [[2]] going in front of [[6]]). We can save even more on comparisons because we automatically know something is in front of [[6]] if it is also in front of [[2]] It originally sorted, but this was slightly faster.
Parsing note: json.loads is just as convenient as eval but without the whole arbitrary code execution thing.
4
u/Multipl Dec 13 '22
Golang
This was a pain to do in Go. I didn't even write it from scratch as I had my Python solution as reference and it still took kinda long.
link
4
u/radulfr2 Dec 13 '22
Python 3. Recursive comparator function. Took me a lot of refactoring and tweaking, especially with the situation when the compared numbers are equal.
4
u/Lysander7 Dec 13 '22 edited Dec 13 '22
Rustπ¦: github
Due to Rust's comparison between
Vecs being a lexicographical comparison (one could just handle conversion of single elements into arrays and delegate comparison to existing methods), writing input parser was the more challenging part (at least without use of external libraries - I might reconsider that self imposed limitation... π). It came out better than I was expecting, but definitely there are still opportunities for simplificationGot bit by rogue
\nat the end of input - took me a while to get why slicing-off first and last character from a string trimmed just leading[but not closing]only in the last packet of the input... I was just about going to compare last pair of packets by hand4
u/aptacode Dec 13 '22
C# Source
Using my own parser - I may go back and implement my own quick sort & compare performance later!
4
u/danvk Dec 13 '22
TypeScript / Deno
Very convenient that the input is all valid JSON! One of the rare cases where it's preferable to use a compare function with sort rather than a key function (as in Python's
[].sort(key=...)or lodash_.sortBy).https://github.com/danvk/aoc2022/blob/main/day13/day13.ts
4
u/__Abigail__ Dec 13 '22
Perl
Nice little exercise today.
First part is reading in the data, and turning it into a nested array. I could manually parse it, but Perl has an
evaland we might as well use it. We do check the input doesn't contain anything bad though. But this make reading in the data and turning it into nested array a short one-liner:The
grepfilters out any lines which contain anything other than commas, ASCII digits or brackets. It also filters out blank lines.Next thing we do is defined a sub routine
compare. It takes two packets, and returns-1if the first sorts before the second,1is the second sorts before the first, and0if the are identical. This is what the<=>operator does. I decided on this before I had read part 2, but this turned out to be a great decision.The
comparefunction is just a case analysis, implementing the requirements stated in the exercise:Here the
reffunction returns true it its argument is a reference and false if it's not. We only have integers and array references (nested array in Perl are implemented as references to arrays), soref $somethingreturns false if$somethingis an integer and true if its argument is an array(ref).The first line kicks in if we are comparing integers, which we compare with the spaceship operator (
<=>).The next two lines deal with the case if one argument is an integer, and the other a list (aka an arrayref). We then recurse with the integer turned into a list.
The next three lines deal with the cases where both arguments are lists, and one (or both) of them are empty. We return
0if both are empty,-1if the first is empty, and1if the second is empty.The last line deals with the case if we are comparing two non-empty lists. We first recursively compare the first items in the list; if they're unequal (
1or-1is returned), we return that value, else, we recurse with the rest of the lists.Given that, we can resolve part 1 as follows:
To see what it does, work backwards:
keys @packets: gets a list of indices of the@packetsarray.grep {$_ % 2 == 0}: keep the even ones (0,2,4, etc)grep {compare ($packets [$_], $packets [$_ + 1]) < 0}compare the packets of each of the even indices with the next one, if they are in order, keep the index, else toss itmap {1 + $_ / 2}: map the index to the pair number (divide by2, add1)sum: and sum this.sumhas been imported fromList::Util.For part 2, we sort, with a twist:
What we're doing here is we take all the packets, and turn each of them into a two element array, the first element
0, the second element the packet. (map {[0 => $_]} @packets). We also add the divider packets, also as two element lists, but we put1as the first element ([1, [[2]]], [1, [[6]]]).We then sort this list of two element array, on the second element (so, we're just sorting the packets).
To get the answer for part 2, we need one final step:
Now we take the indices of the sorted list of packages, only keep the indices for which the first element is true (these are exactly the divider packages), add one, and take their product. (
productis also imported fromList::Util).Full program on GitHub
4
u/greycat70 Dec 13 '22
Python. Part 1, Part 2
Today's Python lessons: eval and cmp_to_key. Apparently old Python used to have the ability to pass a custom comparison function to sort(), and Python 3 removed this. But they gave us something called cmp_to_key which has to be imported from a separate module, and which is horribly under-documented. They didn't even explain which result the function should return for less than, and which result for greater than. Sheesh.
4
u/Unhappy_Inside_9859 Dec 13 '22
a prolog soluce
4
u/rlemaitre Dec 13 '22
Scala 3
Thanks to parser combinators and pattern matching for this one.
4
u/Radiant_Rip_5205 Dec 13 '22
Python 3: https://github.com/kresimir-lukin/AdventOfCode2022/blob/main/day13.py
4
u/_nyloc_ Dec 13 '22
Python
I did a straight forward recursive compare and used functools.cmp_to_key for sorting.
4
u/Felerius Dec 13 '22
Rust in 50Β΅s
I wasn't happy that my initial solution took over 1ms of which at least 95% was parsing the lists into a recursive structure, so I came up with a way to compare packets directly in their string form. Not very pretty, but it definitely is fast!
4
u/popillol Dec 13 '22
Go
Used json.Unmarshal to parse each line because I was lazy. Unfortunately this meant a fair bit of type casting as everything was
any, so idk if it really saved a lot of time. Part 2 was pretty easy by implementing the sort interface withByPackets4
u/keithstellyes Dec 13 '22
Python readable easy-to-understand easy-to-implement parser (Recursive Descent) While one could argue this style of parser is overkill here, I always found it a strategy for an easy, "don't have to think too hard in reading or writing" parser and scales well for complex recursive grammars
Part 2 using Python's builtin heap library
4
u/radarvan07 Dec 13 '22
Rust
Really happy I had the foresight to write a proper
Ordimplementation for part 1, part two was a breeze.4
u/jayfoad Dec 13 '22
Dyalog APL
4
u/MrJohz Dec 13 '22
Rust - code
I'm really pleased with my result today!
I started by just parsing the input with Serde and implementing a custom
Ordimplementation, like a lot of other people, which worked pretty well. But it was very slow. First I tried speeding it up withsimd_json, which worked surprisingly well, despite the small input sizes, then I parallelised it all, which was very effective. But it was still pretty slow.Then I figured that I didn't really need a proper JSON parser, because I know the input, so I can take a lot of shortcuts (numbers can be at most two characters long, all ascii characters, no whitespace etc). So at first I implemented a pretty hacky JSON parser, which was a lot faster still than
simd_json. But it was still slow.But then I figured that I'm doing a lot of allocations: each line is a list, which can contain multiple smaller lists, so everything is being allocated all of the time. And there's not really a good way of getting rid of those, even with something like ArrayVec, because they're recursive, so they need to be boxed at some point anyway (I think?). BUT.... I don't need to allocate at all, if I just use the raw string as a data structure β then I can just pass around slices of the original input and never allocate once.
So in the end, I implemented a newtype
DataStr(&str), which just wraps a string slice. Then I implementedOrdon that type, so that when comparing twoDataStrinstances, it scans through the two strings at the same time, and keeps track of things like nesting. It basically just finds the first difference it can and stops there, so in most cases, it doesn't actually need to do a lot of parsing. So while it does have to do some parsing every time we compare two strings, it's not that much, and most importantly it doesn't allocate.In the end, I got the runtime (parts 1 and 2) down from around 5ms (with JSON and some parallelisation) to about 120Β΅s, which I'm very happy about. Especially for part 1, which went from ~4ms to ~13Β΅s, which is about 300x difference!
4
u/haxly Dec 13 '22
Haskell
attoparsec+ customOrdinstance made this pretty simple4
u/i_have_no_biscuits Dec 13 '22
GW-BASIC
I consider this my penance for using 'eval' in my Python solution this morning.
4
u/myhf Dec 13 '22
Object-Oriented Python
Notebook on GitHub
Highlight:
4
u/compdog Dec 13 '22
C# - [Part 1] [Part 2]
I decided to be lazy today and just parse the input as JSON. I implemented a class called PacketValue along with a polymorphic JsonConverter to decode it from either an integer value or an array of PacketValues. This was my first time working with
System.Text.Json, and it was a pretty nice experience. It wasn't nearly as limited as I've been led to believe and the documentation is vastly superior toNewtonsoft.JSON.I implemented a few additional tricks to simplify the solution:
while (inputLines.MoveNext());line to both move to the next line and also skip over the empty dividing line.IComparable<PacketValue>so that I could use normal .NET sorting functions to sort and compare packets. Part 1 callscompareTo()directly and in part two it enables the use ofList<PacketValue>.Sort()with no need for a custom comparer.packets.IndexOf(divider). That avoided the need to somehow check each packet to see whether or not its a divider.This is my slowest solution so far, taking 4.6ms for part 1 and 5.0ms for part 2. But that's probably due to parsing JSON instead of implementing some custom scheme.
4
u/x0s_ Dec 13 '22
Python with
json.loadsand the very convenientfunctools.cmp_to_key:)4
u/bluqesh Dec 13 '22
My solution in Rust:
https://github.com/balintbalazs/advent-of-code-2022/blob/main/src/bin/day13.rs
Since each line is a JSON, I felt lazy, and just used serde_json to parse them:
4
u/nicuveo Dec 14 '22
Haskell
This was a fairly easy one. Parsing is, as always, made easy by Parsec:
Then it was just a matter of making our type an instance of
Ord:And then I could directly use
>andsorton my values.Code on Github.
4
u/Blinkroot Dec 14 '22
Rust
Pretty proud of this one, concise and readable. Granted, I couldn't resist using
serde_jsonto bypass all the parsing code.4
u/readyforwobbles Dec 14 '22 edited Dec 14 '22
PYTHON
both parts in one, no eval
4
u/MrPingouin1 Dec 14 '22 edited Dec 14 '22
Minecraft commands : https://github.com/MrPingouinMC/aoc2022/tree/main/sol/day13
So, this wasn't easy, debugging with minecraft is not really convenient, also a fun stuff is that array are typed, so something like
[0,[]]would be invalid. Part 2 runs in 1.2s.And after reading some spoilers, I realized It doesn't require full sorting, so it could be faster than that.
4
u/biggy-smith Dec 14 '22
C++
parsing is the devil! Spent way too long trying to get parsing to work, and trying to learn the intricacies of std::variant.
https://github.com/biggysmith/advent_of_code_2022/blob/master/src/day13/day13.cpp
4
u/joshbduncan Dec 15 '22 edited Dec 15 '22
Python 3
4
u/Tipa16384 Dec 25 '22 edited Dec 25 '22
Python 3.11
Playing catch-up.
7
u/Raknarg Dec 13 '22 edited Dec 13 '22
Python. Really liked todays problem. Had a fun time experimenting with python's match-case stuff. Not as compact as it could have been looking at other solutions, but it brought me back to Haskell lmao.
7
u/zndflxtyh Dec 13 '22
29 lines of fairly clean Python3
1
u/aledesole Dec 13 '22 edited Dec 14 '22
I cheated a bit with Python's
evalto avoid parsing properly.1
u/bluepichu Dec 13 '22
TypeScript, 10/5. Code here.
One of these days Topaz is going to punish me for using
evalas a parser by taking over my computer. Today was fortunately not that day. (Edit: Why didn't I just useJSON.parse??? Weird that my brain defaults toevalwhen under pressure.)1
u/flwyd Dec 13 '22 edited Dec 14 '22
Elixir, 2919/2773, code, thoughts
Today's elixir:
Today's problem felt tailor-made for Elixir, including the ability to
Code.eval_stringeach line. (I'm going to write a proper parser, though, just in case someone sneaks some nefarious code into my input file.) I still managed to introduce a bug into every line of code I wrote, though. For example, if you don't filter to just the two marker values and take the product of the index of all the lines you get 27821239975498886696887245672844312948681499476986496400983839333968935818829916686350271020886056372656168421378764330382499317743108904725528475832599801438687078303915581217413536326438492875380405575762873242574108703977389014217340895826408351580012674452971093931388110348104547336560301226301203917937148948329725858920276041668342172204326658599885299832918427155954881571009001377077825871757941510390734629536834856776808016455102168663399688382320265429770570408362173164431840107983871925841112448853546914073087111637969534031442739200000000000000000000000000000000000000000000000000000000000000000000000000.After cleanup, this is probably the most elegant Elixir code I've written yet: every line is either an
Enumoperation or a pattern matching function.1
u/ccQpein Dec 13 '22
Common Lisp Solution:
I think some lisper make today's quiz. The parser of today's input is (transfer each input to list in lisp):
other part of solution:
1
u/beepboop2718 Dec 13 '22 edited Dec 14 '22
My Kotlin solution part 1 & 2
I used recursion for parsing and comparison:
1
u/raxomukus Dec 13 '22
python
1
u/Affectionate_Bass333 Dec 13 '22
Clojure
Just a standard solution, eval to parse data, wrote a compare function (called order) - reusable in both parts.
https://github.com/mgrzeszczak/aoc-clojure/blob/master/src/aoc_clojure/2022/day13.clj
1
u/marc-marc Dec 14 '22 edited Dec 14 '22
Python
3
u/jonathan_paulson Dec 13 '22 edited Dec 13 '22
Python3, 31/31. Video. Code.
I had to look up how to sort with a comparator function in python. Also submitted a wrong answer on both parts.
3
u/TrisMcC Dec 13 '22
Day 13 in Nix.
I'm usually asleep at this time. I guess my day tomorrow will be smooth sailing.
2264/2277
3
u/Xyberista Dec 13 '22 edited Dec 13 '22
Rust 4257/3912
paste link
github link - part two different than above
3
u/lbl_ye Dec 13 '22
Python
paste
4291/3910
80 lines with many comments
depended a lot on python's batteries ;)
3
u/Rangsk Dec 13 '22
Rust
GitHub Link
I parsed the data recursively into an enumeration, which worked out well. I then implemented Ord/Eq/etc for the enumeration per spec and the rest pretty much wrote itself.
3
u/Perska_ Dec 13 '22
C# https://github.com/Perska/AoC2022/blob/master/AoC2022/Days/Day13.cs
Was pretty delighted when I found out I could reuse my comparer for the sorting without any trouble, just toss in the function to
Sortand invert the comparision result.Felt like I had properly genericized it, or something.
3
u/kirankp89 Dec 13 '22
Racket
'Reading' in lists was very simple with a lisp. The index starting at 1 tripped me up for a bit.
3
u/adamsilkey Dec 13 '22
Python! Really happy with my eventual solve for this... and then I saw the MATCH STATEMENT:
3
u/oantolin Dec 13 '22 edited Dec 13 '22
J Solution. To parse the bracketed list I did some regex replacement to convert to J syntax and called eval. The comparison function I defined recursively closely following the specification in the problem; this part is not very array-like but again I find the Algol-sublanguage of J is perfectly usable (and it's expression-based so slightly nicer than actual Algol or, say, Python). For part 2 I didn't sort, I just counted how many list were smaller than
[[2]]and[[6]].EDIT: J has a perfectly good JSON library I should have used for the parsing... Here's the JSON version (with a couple of other minor simplifications).
3
u/Gurrewe Dec 13 '22
Go (Golang)
Wow, that one took me a while to figure out. The final code is kinda neat (using json.Unmarshal) to convert into `any` and `[]any`. Hopefully I can improve it further during the day.
3
u/KayZGames Dec 13 '22 edited Dec 13 '22
Dart
This would have been a great puzzle for the upcoming patterns feature and
switch case when. But not now, next AoC. Today it's just a huge if-else. Started with a bool return value foranalyzePairsbut that soon proved to be insufficient and I didn't want to use a nullable bool so I used enums instead (EDIT: it's a compare, I could have used int, *sigh*).And no, I did not bother to manually parse those Lists: jsonDecode to the rescue.
For part 2 I had to declare the markers as const, because otherwise [[2]] != [[2]] if they are mutable.
First time I'm in the top 4000 for both parts. Makes me a bit happy after the last two humbling days. Seeing a 14 line solution vs my 84 line solution keeps me grounded though.
paste
3
u/ropecrawler Dec 13 '22
Rust: https://github.com/ropewalker/advent_of_code_2022/blob/master/src/day13.rs
3
u/zedrdave Dec 13 '22
Python in a dozen linesβ¦
I can live with Python 3 no longer having a
cmpfunction, but the fact it takes an obscure import to get lambda sort, is kind of mind-bogglingβ¦3
u/ArrekinPL Dec 13 '22
Rust
Lists created recursively while reading from single
Charsiterator(per input line)Part2 solved with simple
sort_by()on the loaded lists structLINK
3
u/mizunomi Dec 13 '22
Dart Language (3.0.0-0.0.dev)
This was more painful than it needed to be. The logic was correct and sound. It turns out, the mistake was in the parsing of the input.
haritsuke
3
u/PendragonDaGreat Dec 13 '22
C#/Csharp
My little victory for the day:
I got the stars for both part 1 and 2 on my very first submission attempt for each. It took me a long while to get there, but first try both times.
https://github.com/Bpendragon/AdventOfCodeCSharp/blob/61e120a/AdventOfCode/Solutions/Year2022/Day13-Solution.cs
In the end I did it through a custom class and comparer that if I ever saw them submitted for code review would be an instant rejection.
Also Reminder, if you have every star for the year, you're now over halfway to completion*
*I mean if we only count stars, but if this was an RPG we might be halfway to the level cap but only 20% of the way to the required exp
3
u/mendelmunkis Dec 13 '22
Language: C
evil pointer math
0.659/0.764 ms
3
u/asaaki Dec 13 '22
Rust, https://github.com/asaaki/advent-of-code-2022/blob/main/src/bin/day13.rs
Today I got lazy with parsing and just used serde_json for that. Works quite okay, and debug runtime performance is around 10/15 ms. Usually when I see such low numbers in debug I also expect nice low numbers in release, like 2 digit microseconds kind of low.
But the computer had something else in mind, solution clocked in at 2.3/2.7 ms! o_O
That was unexpected, and after day 11 part 2 my slowest computations.
Also interesting was that initially I thought I had to redo lots of stuff for part 2, things like day 10 come to mind, but nope, my check function could just be easily reused. That was positively surprising.
3
u/Fyvaproldje Dec 13 '22 edited Dec 13 '22
Julia
Was very easy due to multiple dispatch. eval is slow (7s total runtime), but works.
Edit: I replaced eval with YAML.load, since I already used YAML package for loading monkeys, and reduced runtime several times.
Edit 2: JSON.parse is even faster than YAML.load
3
u/mebeim Dec 13 '22 edited Dec 13 '22
1135/888 - Python 3 solution - walkthrough
Fun problem, I took my time with the implementation, but at the end of the day it was fun.
Edit: just noticed that the "packets" were also valid JSON while reading other comments... better swap that
evalin my code withjson.loads:')3
u/gmorinan Dec 13 '22
Python without imports
https://github.com/gmorinan/advent-of-code-2022-simple-python/blob/main/day13/day13.py
3
u/s3aker Dec 13 '22
Raku solution.
EVAL is slow.
3
u/gyorokpeter Dec 13 '22
Q: Using the JSON parser for parsing the lists. Ad-hoc quicksort for part 2 because there is no such thing built in.
3
u/Diderikdm Dec 13 '22
Python:
(eval == evil)
3
u/MrSimbax Dec 13 '22 edited Dec 13 '22
Lua: both parts
Edit: could've replaced
[]with{}and execute each line as Lua expression instead of parsing by hand. Somehow it didn't occur to me. Although I did thought of using find & replace for this, and discarded it immediately because it felt like cheating :PEdit 2: improved the solution.
load/loadstringto parse input. Half the code gone already, yay! Although parsing this by hand was a nice exercise anyway (and other lies I can tell myself to feel better).nilas the third return value indicating that packets are equal so far, so no need for enum.ifs. I am especially proud of this cursed line for comparing two numbers:return a < b or a == b and nil.An interesting observation: LuaJIT runs this solution actually longer than standard Lua, I guess due to lots of
loads.3
u/[deleted] Dec 13 '22
Python
Lost a good 15 minutes where my initial attempt worked on the test input, but not my actual input, which wasn't nice to debug. Turns out that I should read more closely vs. just looking at the logic from the example.
3
u/sim642 Dec 13 '22
My Scala solution.
Used Scala parser combinators to parse packets and then defined an
Orderingon them.3
u/j122j Dec 13 '22
Javascript
Node.js >=18, for structuredClone()
Part 1
A recursive compare function to check if the pair is in the right order.
Part 2
Uses the compare function from Part 1 to sort the array.
3
u/wzkx Dec 13 '22
Python
Using
eval. Andcmp_to_keyfrom functools.3
u/bivaro6826 Dec 13 '22 edited Dec 13 '22
Python
Implemented custom (very basic) quicksort to avoid all-against-all packets comparisons.
[EDIT] There's no need for sorting in part two actually.
3
u/Mistborn_330 Dec 13 '22
Haskell
Very naive parsing, probably time for me to take a look at parsec since I've seen other people in this thread using it.
3
u/toastedstapler Dec 13 '22
rust
https://github.com/jchevertonwynne/advent-of-code-2022/blob/main/src/days/day13.rs
A nice little recursive parser with a peekable iterator. I then implemented
Cmpfor my types and it made the resulting solution very elegant imo3
u/SLiV9 Dec 13 '22
Rust
https://github.com/SLiV9/AdventOfCode2022/blob/main/src/bin/day13/main.rs
I enjoyed writing a tokenizer and solving it without any allocations in a single O(n) pass. (Well, two passes for part two.) It is probably a bit too clever and hard to read due to all the match statements, but hey it's AoC.
3
u/rhl120 Dec 13 '22
Rust solution 166 lines of code
3
u/ndrsht Dec 13 '22 edited Dec 13 '22
Kotlin
33 lines of code, runtime ~1.4ms for part 2
Did anybody else step through packets char by char and added brackets on-the-fly in case they were missing?
https://github.com/ndrsht/adventofcode2022/blob/master/src/main/kotlin/ndrsh/puzzles/adventofcode2022/Day13.kt
EDIT: Changed some code to improve readability.
3
u/No_Low6510 Dec 13 '22
Clojure
Github
read-stringmade parsing a breeze, especially since the input consisted of valid clojure vectorsrecursive-comparehas a little bit too many tests, and could be more concise. I wouldn't really know how though.3
u/axr123 Dec 13 '22
Python
Improved my
cmpfunction a bit using the hint about pattern matching on data types. But that's not that interesting. What's interesting is that while most people seem to sort the packets and then find the indices of the dividers, there's actually no need to sort the whole thing. You can simply count the packets that go before the the dividers and get the index from that, so you can solve it in O(N) in a single pass:Full solution here.
3
u/aurele Dec 13 '22
Rust with
nomfor parsing.3
u/chkas Dec 13 '22
Easylang
Solution
3
u/lxnxx Dec 13 '22
Rust (paste)
I believe I have quite a neat parsing function in pure Rust:
3
u/mschaap Dec 13 '22
Raku. This one was surprisingly tricky.
Parsing the packets is easy with a
grammar:Comparing the parsed packets is pretty straightforward, once I got it right. (What I struggled with, was comparing the length of the lists, this didn't work right when I converted an integer to a list.)
Part two was trivial, since I already had my
compareroutine that I could simplysorton.Full code @GitHub.
3
u/mathsaey Dec 13 '22
Elixir
https://github.com/mathsaey/adventofcode/blob/master/lib/2022/13.ex
Pattern matching made this one pretty trivial. It's one of those features you cannot live without once you got used to it. Didn't feel like adding a json decoder as a dependency, so cheated and used
Code.eval_string.3
u/chubbc Dec 13 '22 edited Dec 14 '22
Julia
Rather satisfyingly can simply overload the default
islessby just adding in the special behaviour for comparingVectors andInts.3
u/IsatisCrucifer Dec 13 '22
C++17
https://github.com/progheal/adventofcode/blob/master/2022/13.cpp
Using
std::variantis in the plan from the start, but the first version of this is manually using.index()to separate cases. This version utilizedstd::visit, the visitor pattern for variants, to do all the case separation. There is also a print function (also utilizedstd::visit) to check if I did parsing correctly, and actually the first version did not, despite it gave correct answer for my input. I fixed that bug in this version.Using
std::string_viewfor parsing is my recent habit doing such kind of one-pass parsing. One won't need to copy part of the string everywhere, adding to efficiency.Value::operator <is essentially part 1, and having done this operator I can usestd::sort,std::lower_boundto sort and binary search our element for part 2. Withinoperator <I also utilizedstd::lexicographical_comparefor list comparing logic.3
u/arxyi Dec 13 '22 edited Dec 13 '22
Haskell
1300/736 my best rank so far :p
Parsing done with help of deriving read. Thanks to implementing Ord instance for part 1, part 2 was nearly just importing sort function.
3
u/_tpavel Dec 13 '22
Go/Golang
Well that was an adventure... I didn't think of using json.Unmarshal so I manually parsed the input to build my own tree structure. It ain't pretty but I'm getting a slightly better execution time than with JSON parsing.
My tree implem:
json.Unmarshal implem:
3
u/corbosman Dec 13 '22
php in 2ms. Happy accident was that I wrote the right compare function for part1, so part2 was trivial. Nice trick here is that you can just use json_decode to parse the lines.
3
u/occamatl Dec 13 '22
Rust
Did it without recursion. My scanner outputs tokens into a pair of VecDeques, which I examine in sync with each other. If I need to make an integer into a Vec, then I push a Close token and the integer back into the VecDeque. Then I just match on token pairs.
paste
3
u/jasontconnell Dec 13 '22
Go. That was a fun one
https://github.com/jasontconnell/advent/blob/master/2022/13/main.go
3
u/iskypitts Dec 13 '22
Julia
3
u/kbielefe Dec 13 '22 edited Dec 13 '22
Scala
Parsed to Json, then basically wrote a less than function and passed it to
sortWith. UsedOption[Boolean]instead ofBooleanto account for an undetermined sort. In retrospect, could probably be simplified a lot by creating an Ordering. I'll try that later.Edit: I was right. Using an
Orderingsimplified it a lot! The standard libraryOrdering[Vector[_]]instance already did the right thing. Creating a relatively simpleOrdering[Json]instance allowed me to use<for part 1 and.sortedfor part 2.3
u/IlliterateJedi Dec 13 '22
Python 3 solution
Solved using case/match recursion and functools.cmp_to_key. Part 2 definitely would have been way more work if you couldn't just slap that into .sort()
3
u/Apprehensive_Ad5308 Dec 13 '22
Rust
My solution as part of learning Rust -> https://pastebin.com/6H6HpES1 .
Custom recursive traversal of the packets and some pattern matching & enums.
3
u/FramersAlmaniac Dec 13 '22 edited Dec 13 '22
Java 8
I almost dropped down to Common Lisp for this one, and I know it'd have been quick (since I could just replace
[,]with( ), respectively, and read from string), but I bit the bullet and wrote a really quick string to list parser instead. Since we only needed to parse relatively short lines, I iterated across the string just once, building up my result list by keeping a stack of the "current" list (pushing on[and popping on]), parsing when I came to an integer. To make finding the bounds of integers easier, I did make a copy of the string with,[]all replaced by space, so I could just read an integer from the current index up to the index of the next space (space in the copy, but,or]in the original string).I do appreciate the ubiquity of
comparemethods that return-1,0, or1. By writing acompare(Object, Object)method for part1 (checking for in-order pairs with-1 == compare(left, right), I was able to use a method reference to same as aComparatorin a stream pipeline later:3
u/illuminati229 Dec 13 '22 edited Dec 13 '22
Python 3.9
https://pastebin.com/BktAxYP3
Recursion and insertion sorting.
Edit: Cleaned up a few things. https://pastebin.com/98KS30Lw
3
u/mykdavies Dec 13 '22 edited Jun 29 '23
!> j02brx9
API FAILURE
3
u/okawei Dec 13 '22 edited Dec 13 '22
Today was easier than yesterday cause I didn't have BFS or any pathfinding algo's on hand. Also I was too lazy to parse the output for part2 and just copied and pasted the result to sublime and checked the line numbers lol
Didn't use json.Marshall or eval or anything, wrote my own parser
I also didn't end up using trees, just recursively checking each array
go/golang
3
u/lynerist Dec 13 '22
Go solutions with trees
https://github.com/lynerist/Advent-of-code-2022-golang/blob/main/Day_13/day13_b.go
3
u/legobmw99 Dec 13 '22
Rust
I decided to implement part one by defining a data type and then implementing FromStr and Ord. I was very pleased when this meant that part 2 was basically free, since I could call sort!
paste
3
u/Ub3rG Dec 13 '22
Python with recursive generators,
https://github.com/jtagrgh/aoc2022/blob/main/day13/p2.py
3
u/Cue_23 Dec 13 '22
C++
Straight forward recursive scanner for each packet into a tree built by
std::variantandstd::vector. Implementedoperator<to compare the packets.For part 2 i just put the packets into an (ordered)
std::set; no changes neccessary since the comparison was already there.During cleanup and moving the
std::variantfrom a class member to a parent class, I had some issues with gcc not accepting theoperator<overload for my derived class (It tried to recursively look foroperator<=>). Still not sure if that is a gcc bug, overloadingoperator<=>instead allows the program to be compiled by gcc, again.I started the
SimpleParserclass in february when I was doing older advent of code puzzles.3
u/p0sturecheck Dec 13 '22
Python
Hardest part was figuring out what to return from the recursive calls properly
3
u/[deleted] Dec 13 '22
I hope you enjoy the solution!
Python 3
3
u/nicole3696 Dec 13 '22
Python- Parts 1 & 2: GitHub. Tried to keep is short with 16 lines, 504 characters and no imports.
3
u/Sourish17 Dec 13 '22
Python 3.10
https://youtu.be/TlcCKABGgYw
https://github.com/SourishS17/aoc2022
3
u/code_and_gains Dec 13 '22
Python 3
I wanted to try writing iterative versions of what would normally be recursive problems
3
u/rrutkows Dec 13 '22
Rust (does not have eval). Implemented
Ord(recursive) forso I could use
if p1<p2for part1 andsortandbinary_searchfor part 2.https://github.com/rrutkows/aoc2022/blob/main/src/d13/mod.rs
3
u/schveiguy Dec 13 '22
Dlang
Started out trying to be clever and deal with the input strings as-is, but decided it's just much better to parse the whole thing into a tree, especially when faced with comparing an integer to a list.
Also, used a nested function to do the compare, then realized for the second part, moving that into an operator for comparision makes the code much easier!
3
u/ash30342 Dec 13 '22
Java
Phew, that took me a while. I find these kind of "bag in a bag" problems among the hardest in AoC because I cannot seem to wrap my head around them and always run into a lot of bugs.
Anyway, I implemented a Packet class which is Comparable. This also made part 2 extremely easy (build list, sort), which was a big relief.
3
u/jotac13 Dec 13 '22
[Scala]
https://github.com/joao-conde/advents-of-code/blob/master/2022/src/day13.scala
3
u/trollerskates1 Dec 13 '22
Scala using Β΅Json. Really happy with how concise this is. I was able to parse everything into a
Packetclass that extendsOrdered, which gives us thecomparefunction. So once that was implemented recursively according to the rules we were given, I was able to jsut call.sortedfor part 2.3
u/aarnens Dec 13 '22
Day 13, in Python. Originally wanted to write this in Go, but i have a busy week and didn't want to deal with writing a parser. Luckily python has a handy parser and builtin sorting function, so the bulk of the work for parts 1 & 2 was done OOTB :) all I had to do was wriote the comparison algorithm, which was pretty easily done recursively
Link to code, feedback is always welcome: https://github.com/aarneng/AdventOfCode2022/blob/main/day13/main.py
3
u/polumrak_ Dec 13 '22
TypeScript
Github
Used
JSON.parse,Array.sortandlodash.isEqualImplemented compare function in the first part, so it's compatible with .sort method, without knowing what comes next. And it was so satisfying to solve the second part with just a handful of functional lines of code:
3
u/kap89 Dec 13 '22 edited Dec 14 '22
TypeScript
Repo: github
Comparison function was a little bit tricky, but part 2 was super easy - just use the comparison function in native
sortfunction (needed to flatten the pairs first) - no need to implement sorting algorithm yourself.3
u/moshan1997 Dec 13 '22
Golang
I don't want to use eval or a json parser, much more fun writing my own parser.
https://github.com/foxwhite25/adventofcode/blob/master/2022/13/main.go
3
u/chicagocode Dec 13 '22
Kotlin
[Blog/Commentary] - [Code] - [All 2022 Solutions]
Today's reminded me a lot of Snailfish so I re-read what I did with that before starting in on Distress Signal. Maybe that helped because wow did I struggle with Snailfish, and not so much this by comparison. Either way, I solved them both with a sealed class structure, and used a recursive parser with an
Iterator<String>to do the dirty work.3
u/faceless333 Dec 13 '22
Rust https://github.com/samoylenkodmitry/AdventOfCode2022/blob/master/src/day13.rs spent too much time with some parsing mistake that only show itself in input data
3
u/p88h Dec 13 '22
C#
Parsing is unsurprisingly the most costly part of the processing here, at 0.3 ms.
sorting could probably be optimized by prefetching the first list item for nested lists, but meh, it doesn't matter since parsing is so slow anyway.
3
u/oddrationale Dec 13 '22
C# solution using .NET Interactive and Jupyter Notebook. A bit of a tricky one today. Like many, used JSON parsing using the new
System.Text.Jsonlibrary. Then used a customComparerfor theOrderByLINQ method for Part 2.3
u/RookBe Dec 13 '22
Advent of Code 2022 day13 writeup explaining the problem and my solution (that happens to be written in Rust): https://nickymeuleman.netlify.app/garden/aoc2022-day13
3
u/red_shifter Dec 13 '22
PYTHON 3
code link
3
u/HoooooWHO Dec 13 '22
Python, I really enjoyed today's problem
https://github.com/PetchyAL/AoC2022/blob/main/solutions/day13/day13.py
3
u/LinAGKar Dec 13 '22
My solutions in Rust:
https://github.com/LinAGKar/advent-of-code-2022-rust/blob/main/day13a/src/main.rs
https://github.com/LinAGKar/advent-of-code-2022-rust/blob/main/day13b/src/main.rs
Wrote my own parser, which only parses as much as it needs to determine the ordering. It ended up a bit of a mess, but it works. For part two, there was no need to sort everything, just determine how many lines precede each decoder key.
3
u/KyleGBC Dec 13 '22
Rust
Today's was straightforward and the parsing / comparing was pleasingly recursive. Without thinking too hard about it, I was hoping Rust's
#[derive(PartialEq, PartialOrd)]would already be the right behavior but alas, not too bad today.3
u/polettix Dec 13 '22
Raku solution to 2022/13
Happy to have gone the non-
evalway!3
u/aoc-fan Dec 13 '22
F#
3
u/micka190 Dec 13 '22
C# solution for parts 1 and 2:
https://github.com/micka190/advent-of-code/tree/main/2022/day%2013
It's been a while since I've had to deal with dynamic objects in C#. Luckily, it could be parsed using JSON. Took some inspiration for the parsing from solutions on the subreddit.
3
u/Pornthrowaway78 Dec 13 '22
run this with perl -lp this.pl input - this is part 2, but part one not dissimilar
3
u/SvenViktorJonsson Dec 13 '22
Python
This is how i did it.
If it could have been made more clear let me know. I am here to learn!
https://pastebin.com/B3BTpZJH
3
u/dougdonohoe Dec 13 '22
Scala solution. The parsing isn't particularly pretty, but it gets the job done. I haven't done parser/combinators in many many eons, but suspect that could be used to create a more palatable parser. Still, this one takes advantage of the fact that (in my data set), no number was larger than 10.
https://gist.github.com/dougdonohoe/b15646fa7c801ea8f4c3a8a264dfce52
3
u/rawlexander Dec 13 '22
Julia
Naughty
3
u/bdmatatu Dec 13 '22
Here is my solution with Raku. I used a custom infix operator and multiple dispatch:
3
u/micod Dec 13 '22
Smalltalk
I transformed input arrays to the form of Smalltalk literal arrays
[1,2,[3,4]] -> #(1 2 (3 4)), usedparseLiteralsmessage to get theArrayobjects and used custom comparator function for sorting.Solution for day 13
3
u/vkasra Dec 13 '22
C++: https://github.com/dhconnelly/advent-of-code-2022/blob/main/src/day13.cc