-
Notifications
You must be signed in to change notification settings - Fork 0
/
d05.hs
53 lines (42 loc) · 1.37 KB
/
d05.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
module Main where
import Data.List.Split (splitOn)
import Data.List (transpose, foldl')
import Data.Char (isAlpha)
import Data.Array
type Crate = Char
type Stack = [Crate] -- Top is first
type Ship = Array Int Stack
type Move = (Int, Int, Int) -- How many, from where, to where
type Plan = (Ship, [Move])
main :: IO ()
main =
do
(s, moves) <- loadData "a05.txt"
let done1 = foldl' (performMove reverse) s moves
print . getFirsts $ done1
let done2 = foldl' (performMove id) s moves
print . getFirsts $ done2
where
getFirsts :: Ship -> String
getFirsts = map head . elems
performMove :: ([Crate] -> [Crate]) -> Ship -> Move -> Ship
performMove strategy s (what, from, to) = s // [(from, rest), (to, newTo)]
where
(moved, rest) = splitAt what $ s ! from
newTo = strategy moved ++ (s ! to)
loadData :: FilePath -> IO Plan
loadData input =
do
ls <- lines <$> readFile input
let [crates, moves] = splitOn [""] ls
let stacks = parseShip . init $ crates
pure (listArray (1, length stacks) stacks, map parseMove moves)
where
parseShip :: [String] -> [Stack]
parseShip = nonEmpty . map (filter isAlpha) . transpose
parseMove :: String -> Move
parseMove line = (read what, read from, read to)
where
[_, what, _, from, _, to] = words line
nonEmpty :: [String] -> [String]
nonEmpty = filter (not . null)