+/AoC
advent of code
git clone https://git.julia.blue/+/AoC
8e04c2f
master
1from functools import reduce as fold 2from operator import mul 3 4def tobits (s ): 5temp = bin (int (s ,16 ))[2 :] 6dif = len (temp )% 4 7if dif != 0 : 8temp = "0" * (4 - dif )+ temp 9return temp 10 11 12bits = tobits (open ("input" ).read ()) 13 14def parse (b ): 15version = int (b [:3 ],2 ) 16type = int (b [3 :6 ],2 ) 17# print("parsing:", version, type, len(b)) 18# print(b) 19if type == 4 : 20pos = 6 21num = "" 22while True : 23current = b [pos :pos + 5 ] 24num += current [1 :] 25pos += 5 26if current [0 ]== "0" : 27break 28# print("val:", int(num, 2)) 29return (version ,int (num ,2 ),pos ) 30msgs = [] 31if b [6 ]== "1" : 32pos = 18 33subs = int (b [7 :pos ],2 ) 34# print("sub messages:", subs) 35for _ in range (subs ): 36v ,n ,p = parse (b [pos :]) 37msgs .append (n ) 38version += v 39pos += p 40else : 41pos = 22 42size = int (b [7 :22 ],2 ) 43while pos - 22 < size : 44v ,n ,p = parse (b [pos :]) 45msgs .append (n ) 46version += v 47pos += p 48match type : 49case 0 : 50n = sum (msgs ) 51case 1 : 52n = fold (mul ,msgs ) 53case 2 : 54n = min (msgs ) 55case 3 : 56n = max (msgs ) 57case 5 : 58n = msgs [0 ]> msgs [1 ] 59case 6 : 60n = msgs [0 ]< msgs [1 ] 61case 7 : 62n = msgs [0 ]== msgs [1 ] 63case other : 64n = 0 65f"Error: unknown type ( { other } )" ) 66return (version ,int (n ),pos ) 67 68 69parse (bits )[0 ]) 70parse (bits )[1 ])