-
-
Save hlian/57c9c8c0e00aac19f48c80389daa8c62 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module D23 where | |
import BasePrelude hiding ((&), lookup, loop) | |
import Control.Lens | |
import qualified Data.Vector as Vector | |
import D23Input | |
type State = (Int, Map Char Int, Vector Op) | |
env :: Int -> State | |
env i = (0, Map.empty & at 'a' ?~ i, input) | |
lookup :: Param -> State -> Int | |
lookup (R r) st = st ^. _2 . at r . non 0 | |
lookup (I i) _ = i | |
interp :: Op -> State -> State | |
interp (CPY src (R r)) st = | |
st & _2 . at r ?~ lookup src st | |
& _1 +~ 1 | |
interp (INC (R r)) st = | |
st & _2 . at r . _Just +~ 1 | |
& _1 +~ 1 | |
interp (DEC (R r)) st = | |
st & _2 . at r . _Just -~ 1 | |
& _1 +~ 1 | |
interp (JNZ nonzero away) st = | |
st & _1 %~ (\x -> x + (if lookup nonzero st == 0 then 1 else lookup away st)) | |
interp (MULT (R a) (R b) (R c)) st = | |
st & _1 +~ 1 | |
& _2 . at a . _Just .~ lookup (R b) st * lookup (R c) st | |
interp (TGL (R c)) st = | |
st & _1 +~ 1 | |
& _3 . ix (st ^. _1 + lookup (R c) st) %~ toggle | |
toggle :: Op -> Op | |
toggle (CPY a b) = (JNZ a b) | |
toggle (TGL a) = INC a | |
toggle (DEC a) = INC a | |
toggle (INC a) = DEC a | |
toggle (JNZ a b) = CPY a b | |
loop st@(i, env, cmds) | |
| (Vector.null cmds || i >= length cmds) = st | |
| otherwise = loop (interp (cmds ^?! ix i) st) | |
main = | |
print (loop (env 7)) | |
print (loop (env 12)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment