#popcrate
Explore tagged Tumblr posts
Text
Advent of Code 2022, Day 05
Oooof this one was rough. Partly because it required a ton of upfront string manipulation, partly because of figuring out how to do the central action in a functional programming sort of way, and partly because I made things harder on myself by actually implementing things in dataclasses (because this is supposed to be a learning exercise)
import System.IO import Data.Char import Data.List import Data.List.Split
input <- do readFile "input05.txt"
[cratesRaw, instructions] = splitOn "\n\n" input
getNums [_,num_move,_,source,_,dest] = (read num_move, read source,read dest) :: (Int, Int, Int)
moves = map (getNums . words) (lines instructions)
crateT = transpose . lines $ cratesRaw
crates = map (filter isLetter . (!!1)) $ chunksOf 4 crateT
data Stack= Stack [String] deriving (Show)
data Move = Move { amount :: Int, source :: Int, dest :: Int } deriving (Show)
popCrate :: [[a]] -> Int -> ([[a]],a) popCrate l s = ([if n==(s-1) then tail lx else lx| (n, lx) <- zip [0..] l], head (l!!(s-1)))
pushCrate :: ([[a]],a) -> Int -> [[a]] pushCrate (l, s) d = [if n==(d-1) then s:lx else lx| (n, lx) <- zip [0..] l]
singleMove :: [[a]] -> Int -> Int -> [[a]] singleMove l s = pushCrate (popCrate l s)
applyMove :: Stack -> Move -> Stack applyMove (Stack b) (Move 0 s d) = (Stack b) applyMove (Stack b) (Move a s d) = applyMove (Stack (singleMove b s d)) (Move (a-1) s d)
readStack (Stack a) = map head a
readStack $ foldl applyMove (Stack crates) [Move a s d|(a,s,d)<-moves]
multiPopCrate :: [[a]] -> Int -> Int -> ([[a]],[a]) multiPopCrate l q s = ([if n==(s-1) then drop q lx else lx| (n, lx) <- zip [0..] l], take q (l!!(s-1)))
multiPushCrate :: ([[a]],[a]) -> Int -> [[a]] multiPushCrate (l, s) d = [if n==(d-1) then s++lx else lx| (n, lx) <- zip [0..] l]
multiMove :: [[a]] -> Int -> Int -> Int -> [[a]] multiMove l q s = multiPushCrate (multiPopCrate l q s)
applyMove2 :: Stack -> Move -> Stack applyMove2 (Stack b) (Move q s d) = Stack(multiMove b q s d)
readStack $ foldl applyMove2 (Stack crates) [Move a s d|(a,s,d)<-moves]
1 note
·
View note
Photo
Anyone have one of these lying around that they want to part with? Some seem pricey on Etsy, Ebay, & even OfferUp/LetGo. I'd like to turn one to a bottlecap drinko/plinko game sort of like ones I have seen on Pinterest. May hit up Trader Jackxs next weekend to look for one, or inspiration for otber projects. #CokeCrate #CocaColaCrate #PopCrate #SodaCrate #PepsiCrate
0 notes