Last active
May 22, 2022 15:29
-
-
Save Mu-adventofcode/c66306388646b3dda649cf4aaa2b0ef1 to your computer and use it in GitHub Desktop.
Advent of Code 2021 day 16 part 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def version_sum(packet): | |
if int(packet, 2) == 0: # padding with zeroes | |
return 0, None | |
version = int(packet[:3], 2) | |
ptype = int(packet[3:6], 2) | |
if ptype == 4: # literal packet | |
rest = packet[6:] | |
while rest[0] == "1": | |
rest = rest[5:] | |
return version, rest[5:] | |
else: # operator packet | |
ltype = packet[6] | |
rest = packet[22:] if ltype == "0" else packet[18:] | |
subtotals = 0 | |
while rest: | |
subt, rest = version_sum(rest) | |
subtotals += subt | |
return version + subtotals, None | |
hexstr = open("input_16.txt").read().strip() | |
packet = "".join(f"{int(ch, 16):04b}" for ch in hexstr) | |
result, _ = version_sum(packet) | |
print(result) |
I agree. Edited the source accordingly (revision 5).
Revision 6 is a major update that:
- has no need to calculate literal values (just consumes the literal packet)
- recurses the parsing without passing along the subtotal of versions
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd prefer
group[-4:]
instead ofgroup[1:5]
.