Add description for day 16
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
@@ -3,8 +3,14 @@ from pathlib import Path
|
|||||||
from math import prod
|
from math import prod
|
||||||
|
|
||||||
|
|
||||||
def get_next_packet(msg, start, packets, res=0):
|
def get_next_packet(msg, idx, packets, res=0):
|
||||||
idx = start
|
"""The function is called recursively and will read a single packet starting at index 'idx' in
|
||||||
|
'msg'. The packet will be appended to the 'packets' list. For each packet the type_id and a
|
||||||
|
payload is stored. The payload is a literal for packets of type 4 or will be filled with
|
||||||
|
subsequent packages for other types by recursion of this function. The version will be added to
|
||||||
|
the result.
|
||||||
|
At the end the updated index and result will be returned.
|
||||||
|
"""
|
||||||
if (idx+11) >= len(msg):
|
if (idx+11) >= len(msg):
|
||||||
idx = -1
|
idx = -1
|
||||||
return idx, res
|
return idx, res
|
||||||
@@ -41,11 +47,12 @@ def get_next_packet(msg, start, packets, res=0):
|
|||||||
next_idx = idx + length
|
next_idx = idx + length
|
||||||
while idx < next_idx:
|
while idx < next_idx:
|
||||||
idx, res = get_next_packet(msg, idx, payload, res)
|
idx, res = get_next_packet(msg, idx, payload, res)
|
||||||
packets.append({'version': version, 'type_id': type_id, 'payload': payload})
|
packets.append({'type_id': type_id, 'payload': payload})
|
||||||
return idx, res
|
return idx, res
|
||||||
|
|
||||||
|
|
||||||
def calc_result(packets):
|
def calc_result(packets):
|
||||||
|
"""The function recursively steps through the packets and performs the defined calculations."""
|
||||||
res = 0
|
res = 0
|
||||||
for p in packets:
|
for p in packets:
|
||||||
match p['type_id']:
|
match p['type_id']:
|
||||||
@@ -74,6 +81,13 @@ def calc_result(packets):
|
|||||||
|
|
||||||
|
|
||||||
def solve(input):
|
def solve(input):
|
||||||
|
"""Part 1 and part 2 are solved in one go so we don't have to parse the bitstream twice. We
|
||||||
|
start by stripping newline and zeros at the end of the input line, convert it to an integer
|
||||||
|
with base 16 (hexadecimal) and back to a binary string. The bin() function adds '0b' at the
|
||||||
|
beginning so we only store te actual binary data. Afterwards we need to add zeros in the
|
||||||
|
beginning until the binary string has a length of four times the hexadecimal representation
|
||||||
|
(Each hex digit is four binary digits).
|
||||||
|
"""
|
||||||
result_p1 = 0
|
result_p1 = 0
|
||||||
line = input[0].rstrip().strip('0')
|
line = input[0].rstrip().strip('0')
|
||||||
msg = bin(int(line, 16))[2:]
|
msg = bin(int(line, 16))[2:]
|
||||||
|
|||||||
Reference in New Issue
Block a user