added day 16
This commit is contained in:
56
16/solve01.py
Normal file
56
16/solve01.py
Normal file
@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import copy
|
||||
|
||||
def decode_packet(packet):
|
||||
|
||||
# import pdb; pdb.set_trace()
|
||||
|
||||
result = 0
|
||||
# get version
|
||||
v = int(packet[:3], 2)
|
||||
packet = packet[3:]
|
||||
result += v
|
||||
|
||||
# get type
|
||||
t = int(packet[:3], 2)
|
||||
packet = packet[3:]
|
||||
|
||||
# literal, no other sub packets
|
||||
if t == 4:
|
||||
while True:
|
||||
l = packet[:5]
|
||||
packet = packet[5:]
|
||||
if int(l[0],2) == 0:
|
||||
break
|
||||
return (result, packet)
|
||||
|
||||
i = int(packet[:1], 2)
|
||||
packet = packet[1:]
|
||||
if i == 0:
|
||||
l = int(packet[:15], 2)
|
||||
packet = packet[15:]
|
||||
n_packet = packet[:l]
|
||||
packet = packet[l:]
|
||||
while (len(n_packet)):
|
||||
(tmp_r, tmp_p) = decode_packet(n_packet)
|
||||
n_packet = tmp_p
|
||||
result += tmp_r
|
||||
return(result, packet)
|
||||
|
||||
if i == 1:
|
||||
l = int(packet[:11], 2)
|
||||
packet = packet[11:]
|
||||
for i in range(l):
|
||||
(tmp_r, tmp_p) = decode_packet(packet)
|
||||
packet = tmp_p
|
||||
result += tmp_r
|
||||
return (result, packet)
|
||||
|
||||
return (result, packet)
|
||||
|
||||
with open("input01.txt","r") as f:
|
||||
for packet in f:
|
||||
packet = bin(int('1'+packet.strip(), 16))[3:]
|
||||
(result, packet) = decode_packet(packet)
|
||||
print(result)
|
||||
Reference in New Issue
Block a user