adventofcode/2022/day05.hs

48 lines
1.4 KiB
Haskell

import Data.List (transpose, delete)
import Data.List.Split (chunksOf, splitOn)
import Data.Char (isSpace)
import Debug.Trace (traceShowId, traceShow)
data Command = Move {amount :: Int, from :: Int, to :: Int} deriving Show
type State = [[Char]]
parseInit :: [String] -> State
parseInit s = map (dropWhile isSpace . init . (!!1)) (chunksOf 4 $ transpose s)
parseCmds :: [String] -> [Command]
parseCmds s = map readCmd s where
readCmd s = let w = words s in Move (read (w !! 1)) (read (w !! 3) - 1) (read (w !! 5) - 1)
listApp :: Int -> (a -> a) -> [a] -> [a]
listApp 0 f (x:xs) = f x : xs
listApp n f (x:xs) = x : listApp (n-1) f xs
move1 :: (Int, Int) -> State -> State
move1 (from, to) state = addTo $ popFrom state where
popFrom = listApp from tail
elem = head (state !! from)
addTo = listApp to (elem:)
moveN :: Command -> State -> State
moveN (Move 0 from to) = id
moveN (Move n from to) = moveN (Move (n-1) from to) . move1 (from,to)
moveN2 :: Command -> State -> State
moveN2 (Move amount from to) state = addTo $ popFrom state where
popFrom = listApp from (drop amount)
elems = take amount (state !! from)
addTo = listApp to (elems ++ )
main :: IO ()
main = do
[init', cmds'] <- splitOn [""] . lines <$> getContents
let init = parseInit init'
let cmds = parseCmds cmds'
putStr "part 1: "
print $ map head $ foldl (flip moveN) init cmds
putStr "part 2: "
print $ map head $ foldl (flip moveN2) init cmds