Skip to content

Instantly share code, notes, and snippets.

@Mu-adventofcode
Last active May 22, 2022 15:29
Show Gist options
  • Save Mu-adventofcode/c66306388646b3dda649cf4aaa2b0ef1 to your computer and use it in GitHub Desktop.
Save Mu-adventofcode/c66306388646b3dda649cf4aaa2b0ef1 to your computer and use it in GitHub Desktop.
Advent of Code 2021 day 16 part 1
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)
@lightningbrie
Copy link

I'd prefer group[-4:] instead of group[1:5].

@Mu-adventofcode
Copy link
Author

Mu-adventofcode commented May 22, 2022

I agree. Edited the source accordingly (revision 5).

@Mu-adventofcode
Copy link
Author

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