-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay5.hs
62 lines (51 loc) · 1.85 KB
/
Day5.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module Day5
( part1
, part2
) where
import Data.List.Split (chunksOf, splitOn)
import Data.Char (digitToInt)
import Data.IntMap as I (IntMap, elems, fromList, insert, (!))
import Data.List (transpose)
import Data.Sequence as S (Seq ((:<|)), fromList, splitAt, (><))
day = 5
newPileFromString :: IntMap String -> String -> IntMap String
newPileFromString pile orders = insert from moved . insert to piled $ pile
where
parsedOrders = words orders
count = read $ parsedOrders !! 1
from = read $ parsedOrders !! 3
to = read $ parsedOrders !! 5
(moved, piled) = move count (pile ! from, pile ! to)
move 0 (f, t) = (f, t)
move x (f:fs, t) = move (x - 1) (fs, f : t)
newPileFromSeq :: IntMap (Seq Char) -> String -> IntMap (Seq Char)
newPileFromSeq pile orders = insert from moved . insert to piled $ pile
where
parsedOrders = words orders
count = read $ parsedOrders !! 1
from = read $ parsedOrders !! 3
to = read $ parsedOrders !! 5
(moving, moved) = S.splitAt count $ pile ! from
piled = moving >< pile ! to
cm :: String -> [[String]]
cm = map lines . splitOn "\n\n"
initialState = map (filter (/= ' ')) . transpose . map (map (!! 1) . chunksOf 4)
initialStateString = I.fromList . map (\x -> (digitToInt . last $ x, init x))
initialStateSeq =
I.fromList . map (\x -> (digitToInt . last $ x, S.fromList . init $ x))
part1 :: Bool -> String -> String
part1 _ input =
show .
map head .
elems . foldl newPileFromString (initialStateString . initialState $ crates) $
movements
where
(crates:movements:_) = cm input
part2 :: Bool -> String -> String
part2 _ input =
show .
map (\(a :<| _) -> a) .
elems . foldl newPileFromSeq (initialStateSeq . initialState $ crates) $
movements
where
(crates:movements:_) = cm input