-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12.coffee
91 lines (78 loc) · 934 Bytes
/
12.coffee
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
_log = require 'ololog'
input = '''
cpy 1 a
cpy 1 b
cpy 26 d
jnz c 2
jnz 1 5
cpy 7 c
inc d
dec c
jnz c -2
cpy a c
inc a
dec b
jnz b -2
cpy c b
dec d
jnz d -6
cpy 13 c
cpy 14 d
inc a
dec d
jnz d -2
dec c
jnz c -5
'''
parse = ( input )->
input.split('\n').map (a)->a.split ' '
exec = ( prog, st )->
_log st
cycles = 0
i = 0
while 0 <= i < prog.length
++cycles
l = prog[i]
#_log i, l, st
switch l[0]
when 'cpy'
st[l[2]] = st[l[1]] ? +l[1]
when 'inc'
++st[l[1]]
when 'dec'
--st[l[1]]
when 'jnz'
if ( st[l[1]] ? +l[1] ) isnt 0
i += st[l[2]] ? +l[2]
continue
else
throw new Error 'invalid instruction', l
++i
_log cycles, 'ticks'
st
test = '''
cpy 41 a
inc a
inc a
dec a
jnz a 2
dec a
'''
try
st =
a:0
b:0
c:0
d:0
prog = parse input
st = exec prog, st
_log.yellow st
st =
a:0
b:0
c:1
d:0
st = exec prog, st
_log.yellow st
catch e
_log.red e