r/adventofcode • • Dec 16 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 16 Solutions -🎄-

NEW AND NOTEWORTHY

DO NOT POST SPOILERS IN THREAD TITLES!

  • The only exception is for Help posts but even then, try not to.
  • Your title should already include the standardized format which in and of itself is a built-in spoiler implication:
  • [YEAR Day # (Part X)] [language if applicable] Post Title
  • The mod team has been cracking down on this but it's getting out of hand; be warned that we'll be removing posts with spoilers in the thread titles.

KEEP /r/adventofcode SFW (safe for work)!

  • Advent of Code is played by underage folks, students, professional coders, corporate hackathon-esques, etc.
  • SFW means no naughty language, naughty memes, or naughty anything.
  • Keep your comments, posts, and memes professional!

--- Day 16: Packet Decoder ---


Post your code solution in this megathread.

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:27:29, megathread unlocked!

46 Upvotes

677 comments sorted by

View all comments

1

u/FordyO_o Dec 16 '21 edited Dec 17 '21

PHP

Spent 99% of the time trying to get PHP to correctly convert the hex to bin (it was chopping off leading 0's)

Ended up having to convert each char individually and str_pad to 4 bytes

$bits = implode('', array_map(fn($h) => str_pad(base_convert($h, 16, 2), 4, "0", STR_PAD_LEFT), str_split($input)));

Pt2 was relatively easy as I'd parsed the whole packet tree already

1

u/daggerdragon Dec 16 '21

Your code is hard to read on old.reddit when everything is inlined like this and gets cut off at the edge of the window. Please edit it to use a proper code block as per our posting guidelines in the wiki: How do I format code?

1

u/[deleted] Dec 16 '21

May I?

# Input is hex, output is bin (each 4 bits padded with '0', if needed)
$msg = implode('', array_map(fn($char) => substr('000' . decbin(hexdec($char)), -4), str_split($msg)));

1

u/FordyO_o Dec 16 '21

Is this faster than my method, seems to be doing mostly the same thing (I actually tried the hexdec => decbin approach before moving to base_convert)