-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathpart2.lua
More file actions
executable file
·139 lines (130 loc) · 2.69 KB
/
part2.lua
File metadata and controls
executable file
·139 lines (130 loc) · 2.69 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env lua
local hex = {}
function hextable()
local s = '0123456789abcdef'
for i = 1, #s do
hex[string.byte(s, i)] = i-1
end
end
function hex2bin(s)
local bin = {}
for i = 1, #s do
x = hex[string.byte(s, i)]
bin[#bin+1] = x >> 3
bin[#bin+1] = (x >> 2) & 1
bin[#bin+1] = (x >> 1) & 1
bin[#bin+1] = x & 1
end
return bin
end
function bits2dec(bits, i, k)
local n = 0
for j = i, i + k - 1 do
n = n * 2 + bits[j]
end
return n
end
function parse_version(bits, i)
return bits2dec(bits, i, 3), i + 3
end
function parse_type(bits, i)
local types = {'sum', 'prod', 'min', 'max', 'number', 'gt', 'lt', 'eq'}
local t = bits2dec(bits, i, 3)
return types[t + 1], i + 3
end
function parse_number(bits, i)
local n = 0
while true do
n = n * 16 + bits2dec(bits, i + 1, 4)
if bits[i] == 0 then
break
else
i = i + 5
end
end
return n, i + 5
end
function parse_operator(bits, i)
local op = {}
if bits[i] == 0 then
local len = bits2dec(bits, i + 1, 15)
i = i + 16
j = i
repeat
op[#op+1], j = parse(bits, j)
until j == i + len
i = j
else
local count = bits2dec(bits, i + 1, 11)
i = i + 12
for j = 1, count do
op[j], i = parse(bits, i)
end
end
return op, i
end
function parse(bits, i)
local e = {}
e.version, i = parse_version(bits, i)
e.type, i = parse_type(bits, i)
if e.type == 'number' then
e.value, i = parse_number(bits, i)
else
e.op, i = parse_operator(bits, i)
end
return e, i
end
function eval(t)
local r
if t.type == 'sum' then
r = 0
for k = 1, #t.op do
r = r + eval(t.op[k])
end
elseif t.type == 'prod' then
r = 1
for k = 1, #t.op do
r = r * eval(t.op[k])
end
elseif t.type == 'min' then
r = eval(t.op[1])
for k = 2, #t.op do
local s = eval(t.op[k])
if s < r then
r = s
end
end
elseif t.type == 'max' then
r = eval(t.op[1])
for k = 2, #t.op do
local s = eval(t.op[k])
if s > r then
r = s
end
end
elseif t.type == 'number' then
r = t.value
elseif t.type == 'gt' then
if eval(t.op[1]) > eval(t.op[2]) then
r = 1
else
r = 0
end
elseif t.type == 'lt' then
if eval(t.op[1]) < eval(t.op[2]) then
r = 1
else
r = 0
end
else
if eval(t.op[1]) == eval(t.op[2]) then
r = 1
else
r = 0
end
end
return r
end
hextable()
t = parse(hex2bin(string.lower(io.read())), 1)
print(eval(t))