22
[aoc20.git] / 8 / one.icl
1 module one
2
3 import StdEnv
4
5 read :: *File -> [Instr]
6 read f
7 # (l, f) = freadline f
8 | l.[size l - 1] <> '\n' = []
9 = [toInstr [c\\c<-:l | c <> '\n']:read f]
10 where
11 toInstr ['nop ':rs] = Nop (toInt (toString rs))
12 toInstr ['acc ':rs] = Acc (toInt (toString rs))
13 toInstr ['jmp ':rs] = Jmp (toInt (toString rs))
14
15 :: Instr = Nop Int | Acc Int | Jmp Int
16
17 Start w
18 # (io, w) = stdio w
19 # instr = read io
20 # instr = {c\\c<-instr}
21 = (one instr, two instr)
22
23 one = fst o interpret
24 two is = [ acc \\i<-:is & pc<-[0..]
25 , let (acc, t) = interpret (update {i\\i<-:is} pc (swapnop i))
26 | t]
27 where
28 swapnop (Nop i) = Jmp i
29 swapnop (Jmp i) = Nop i
30 swapnop i = i
31
32 interpret :: {Instr} -> (Int, Bool)
33 interpret instr = int [] 0 0
34 where
35 int vis pc acc
36 | pc >= size instr = (acc, True) // terminated
37 | isMember pc vis = (acc, False) // inf loop
38 = case instr.[pc] of
39 Nop _ = int [pc:vis] (1 + pc) acc
40 Acc i = int [pc:vis] (1 + pc) (i + acc)
41 Jmp i = int [pc:vis] (i + pc) acc