r/adventofcode • • Dec 12 '16

SOLUTION MEGATHREAD --- 2016 Day 12 Solutions ---

--- Day 12: Leonardo's Monorail ---

Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with "Help".


MUCH ADVENT. SUCH OF. VERY CODE. SO MANDATORY. [?]

This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

8 Upvotes

159 comments sorted by

View all comments

Show parent comment

2

u/Tarmen Dec 13 '16 edited Dec 13 '16

I really want to learn lenses but I find examples super hard to read and the cheat sheet on github is far from complete.

Anyway, I just threw the state monad at it and the problem became pretty straightforward:

import Data.Map as M
import Control.Monad.State
import Data.Char
import System.IO

main = process . parseAll <$> readFile "in12.txt" >>= print

process :: [Op] -> Definitions
process commands = evalState go (0, M.empty)
  where 
    go = do
      (i, m) <- get
      if i >= length commands
      then return m
      else do
        put $ case commands !! i of
          (Copy from to)   -> (succ i, M.insert to (loadVal from m) m)
          (Inc reg)        -> (succ i, M.adjust succ reg m)
          (Dec reg)        -> (succ i, M.adjust pred reg m)
          (Jump cond delta) -> let i' = if 0 /= loadVal cond m then i+delta else i+1
                               in (i', m)
        go

type Definitions = M.Map Char Int
data Value = Register Char | Constant Int
data Op = Copy Value Char
          | Jump Value Int
          | Inc Char
          | Dec Char
loadVal (Register r) state = maybe 0 id $ M.lookup r state
loadVal (Constant const) _ = const
----------------------------------------------------------------------------------

parseAll = fmap parse . lines 
parse = go . words
  where go ["cpy", a, b] = Copy (pVal a) (pReg b)
        go ["jnz", a, b] = Jump (pVal a) (pConst b)
        go ["inc", a]    = Inc (pReg a)
        go ["dec", a]    = Dec (pReg a)

        pReg = head
        pConst = read
        pVal i = if any isAlpha i then Register (pReg i) else Constant (pConst i)