-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday16.krk
92 lines (77 loc) · 2.12 KB
/
day16.krk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/env kuroko
'''
Template
'''
import fileio
import kuroko
let data
with fileio.open(kuroko.argv[1] if len(kuroko.argv) > 1 else kuroko.argv[0].replace('.krk','.txt'),'r') as f:
data = f.readlines()
let line = [line.strip() for line in data][0]
def toBin(x):
let s = bin(int('0x'+x))[2:]
return '0' * (4 - len(s)) + s
let asBits = ''.join(toBin(c) for c in line)
print(asBits)
let index = 0
def readBits(n):
let out = int('0b' + asBits[index:index+n])
index += n
return out
def readBitsLit(n):
let out = asBits[index:index+n]
index += n
return out
let total = 0
def mul(s):
let out = s[0]
for p in s[1:]:
out *= p
return out
let ops = {
0: sum,
1: mul,
2: min,
3: max,
5: lambda s: int(s[0] > s[1]),
6: lambda s: int(s[0] < s[1]),
7: lambda s: int(s[0] == s[1]),
}
let opnames = {
0: 'sum', 1: 'mul', 2: 'min', 3: 'max',
4: 'literal', 5: 'gt', 6: 'lt', 7: 'eq'
}
def readPacket(depth=0):
let version = readBits(3)
total += version
let packet = readBits(3)
print(' ' * depth, 'version',version,'type',packet,opnames[packet])
if packet == 4:
let bitstream = ''
while True:
let notLast = readBits(1)
let bits = readBitsLit(4)
bitstream = bitstream + bits
if not notLast:
break
print(' ' * depth, 'literal', bitstream,'=',int('0b'+bitstream))
return int('0b' + bitstream)
else:
let lenType = readBits(1)
let sub = []
if lenType == 0: # 15 bits
let length = readBits(15)
print(' ' * depth, ' len', length, 'bits')
let end = index + length
while index < end:
sub.append(readPacket(depth+2))
else:
let packets = readBits(11)
print(' ' * depth, ' len', packets, 'packets')
for i=0;i<packets;i++:
sub.append(readPacket(depth+2))
let answer = ops[packet](sub)
print(' '*depth,opnames[packet],'=',answer)
return answer
print(readPacket())
print('total of versions =',total)