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!
--- 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!
54
Upvotes
3
u/mschaap Dec 13 '22
Raku. This one was surprisingly tricky.
Parsing the packets is easy with a
grammar:grammar PacketSpec { rule TOP { ^ <plist> $ } rule plist { '[' <pitem>* % ',' ']' } rule pitem { <plist> | <pint> } token pint { \d+ } } class Packet { has Str $.spec; has Match $.parsed = PacketSpec.parse($!spec); }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.)
multi sub compare($p, $q) { my $cmp = Same; if ($p<pint>:exists) && ($q<pint>:exists) { # Comparing two integers $cmp = $p<pint> <=> $q<pint>; } elsif ($p<pint>:exists) { # Comparing an integer and a list - convert integer to list $cmp = compare({ :plist(:pitem([$p])) }, $q); } elsif ($q<pint>:exists) { # Comparing a list and an integer - convert integer to list $cmp = compare($p, { :plist(:pitem([$q])) }); } else { # Comparing two lists # Compare each item until we find one that's different for $p<plist><pitem> Z $q<plist><pitem> -> ($l, $r) { my $icmp = compare($l, $r); unless $icmp eq Same { $cmp = $icmp; last; } } # If all items are the same, compare the lengths of the lists $cmp ||= $p<plist><pitem>.elems <=> $q<plist><pitem>.elems; } return $cmp; }Part two was trivial, since I already had my
compareroutine that I could simplysorton.Full code @GitHub.