From cadeaf1bba84b4bef4f3919196e5d07c2c4059de Mon Sep 17 00:00:00 2001 From: Pascal Lais Date: Thu, 16 Dec 2021 17:59:47 +0100 Subject: [PATCH] Add description for day 16 --- day-16/day-16.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/day-16/day-16.py b/day-16/day-16.py index 4c42f22..8886a69 100644 --- a/day-16/day-16.py +++ b/day-16/day-16.py @@ -3,8 +3,14 @@ from pathlib import Path from math import prod -def get_next_packet(msg, start, packets, res=0): - idx = start +def get_next_packet(msg, idx, packets, res=0): + """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): idx = -1 return idx, res @@ -41,11 +47,12 @@ def get_next_packet(msg, start, packets, res=0): next_idx = idx + length while idx < next_idx: 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 def calc_result(packets): + """The function recursively steps through the packets and performs the defined calculations.""" res = 0 for p in packets: match p['type_id']: @@ -74,6 +81,13 @@ def calc_result(packets): 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 line = input[0].rstrip().strip('0') msg = bin(int(line, 16))[2:]