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
|
require "ext"
local cpu = {
r = {x = 1},
isa = {
addx = {
nargs = 1,
cycles = 2,
f = function(self,v)
self.r.x = self.r.x + tonumber(v)
end
},
noop = {
nargs = 0,
cycles = 1,
f = function(self) end
}
}
}
local strength_sum = 0
local cycle = 1
for line in io.lines() do
local parts = {}
for part in line:gmatch("(%S+)") do
table.insert(parts,part)
end
local insn = table.remove(parts,1)
local ins = cpu.isa[insn]
assertf(ins, "No instruction %s in %s",insn,line)
for i = cycle,cycle + ins.cycles - 1 do
if (i - 20) % 40 == 0 then
local strength = i * cpu.r.x
strength_sum = strength_sum + strength
break
end
end
cycle = cycle + ins.cycles
ins.f(cpu,table.unpack(parts))
end
print(strength_sum)
|