summaryrefslogtreecommitdiff
path: root/2020/8.hs
blob: bc90351441ba16f83485a5f0a8fa575fe3c30e7e (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
35
module Main where

import Data.Maybe (catMaybes)
import qualified Data.Set as Set

import Asm
import Input


main :: IO ()
main = do
    input <- getInput 8
    let prog = programFrom (map parseIns input)

    let nodupPredicate set state
          | sIP state `Set.member` set = (set, True)
          | sIP state == programLength prog = (set, True)
          | otherwise = (Set.insert (sIP state) set, False)

    print (sAcc (evalUntil nodupPredicate prog mempty initState))

    let overriders = catMaybes
            [case programGet prog i of
               NOP a -> Just $ \j -> if j == i then Just (JMP a) else Nothing
               JMP a -> Just $ \j -> if j == i then Just (NOP a) else Nothing
               _     -> Nothing
            | i <- [0 .. programLength prog - 1]]

        results =
            [state
            | ovr <- overriders
            , let state = evalUntil nodupPredicate (prog `withOverrider` ovr) mempty initState
            , sIP state == programLength prog]

    print (sAcc (head results))