blob: 846c3dfce4b1736376574ed6780d792ac61bd25e (
plain)
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
|
module Day8A where
import System.Environment (getArgs)
data Instruction = Nop | Acc Int | Jmp Int
deriving (Eq, Show, Ord)
readSigned :: String -> Int
readSigned ('+':xs) = read xs
readSigned xs = read xs
parseInstruction :: String -> Instruction
parseInstruction xs | ins == "nop" = Nop
| ins == "acc" = Acc num
| ins == "jmp" = Jmp num
where ins = take 3 xs
num = readSigned $ drop 4 xs
execUntilLoop :: [Instruction] -> [Int] -> Int -> Int -> Int
execUntilLoop is vs ip ax | ip `elem` vs = ax
| otherwise = case ins of Nop -> execUntilLoop is vs' (ip + 1) ax
Acc x -> execUntilLoop is vs' (ip + 1) (ax + x)
Jmp x -> execUntilLoop is vs' (ip + x) ax
where ins = is!!ip
vs' = ip : vs
main :: IO ()
main = do
args <- getArgs;
content <- readFile $ head args;
let l = lines content;
let is = map parseInstruction l;
print $ execUntilLoop is [] 0 0;
return ();
|