1
0
Fork 0

solve 2022 day 5 pt 1 & 2

This commit is contained in:
Sloane Perrault 2022-12-08 22:14:18 -05:00
parent 746d4f5d9f
commit 217c8cde38
No known key found for this signature in database
2 changed files with 20 additions and 9 deletions

View file

@ -2,9 +2,8 @@ module Aoc.Day5 (solve) where
import Aoc (runReadP) import Aoc (runReadP)
import Data.Char (isDigit) import Data.Char (isDigit)
import Data.Maybe
import Data.List (transpose) import Data.List (transpose)
import Data.IntMap.Strict (IntMap) import Data.IntMap.Strict (IntMap, (!))
import qualified Data.IntMap.Strict as IntMap import qualified Data.IntMap.Strict as IntMap
import Text.ParserCombinators.ReadP import Text.ParserCombinators.ReadP
@ -53,12 +52,18 @@ parseInput input = Input { state = state, procedure = procedure }
procedureContents = drop 1 $ dropWhile (/= "") $ lines input procedureContents = drop 1 $ dropWhile (/= "") $ lines input
procedure = map parseMove procedureContents procedure = map parseMove procedureContents
doMove :: Move -> State -> State doMove :: State -> Move -> State
doMove m s = s' doMove stacks (Move n x y) = IntMap.insert x newX (IntMap.insert y newY stacks)
where where
(forTo, backToFrom) = splitAt (amount m) $ fromJust $ IntMap.lookup (from m) s (toPush, newX) = splitAt n (stacks ! x)
addToTo to' = Just $ (reverse forTo) ++ to' newY = reverse toPush ++ stacks ! y
s' = IntMap.update addToTo (to m) $ IntMap.insert (from m) backToFrom s
-- no reverse
doMove' :: State -> Move -> State
doMove' stacks (Move n x y) = IntMap.insert x newX (IntMap.insert y newY stacks)
where
(toPush, newX) = splitAt n (stacks ! x)
newY = toPush ++ stacks ! y
stackLabel :: Stack -> String stackLabel :: Stack -> String
stackLabel [] = "" stackLabel [] = ""
@ -68,7 +73,13 @@ message :: State -> String
message s = concat $ map stackLabel $ IntMap.elems s message s = concat $ map stackLabel $ IntMap.elems s
solve :: Integer -> String -> String solve :: Integer -> String -> String
solve 1 input = message $ foldr doMove state' procedure' solve 1 input = message $ foldl doMove state' procedure'
where
input' = parseInput input
state' = state input'
procedure' = procedure input'
solve 2 input = message $ foldl doMove' state' procedure'
where where
input' = parseInput input input' = parseInput input
state' = state input' state' = state input'

View file

@ -13,7 +13,7 @@
1. 2019 1. 2019
1. [2020] **17/50** 🌟 1. [2020] **17/50** 🌟
1. [2021] **43/50** 🌟 1. [2021] **43/50** 🌟
1. [2022] **8/50** 🌟 1. [2022] **10/50** 🌟
[2015]: ./2015 [2015]: ./2015
[2017]: ./2017 [2017]: ./2017