1 module Main(main) where
3 import Data.List.Split (splitOn)
4 import Data.Char (isSpace)
6 type Chunk = (Int, String)
10 textL <- readFile "advent09.txt"
11 let text = filter (not . isSpace) textL
15 part1 :: String -> IO ()
17 print $ cLength $ decompress text
19 part2 :: String -> IO ()
21 print $ cLength $ decompress2 text
24 decompress :: String -> [Chunk]
27 then (1, pre):(num, chunk):drest
30 (pre, msuf) = span ('(' /= ) text
31 (marker, suf) = span (')' /= ) msuf
32 ln = splitOn "x" (tail marker)
33 len = read (ln!!0) :: Int
34 num = read (ln!!1) :: Int
35 (chunk, remainder) = splitAt len (tail suf)
36 drest = decompress remainder
38 decompress2 :: String -> [Chunk]
41 then [(1, pre)] ++ mulDchunks ++ drest
44 (pre, msuf) = span ('(' /= ) text
45 (marker, suf) = span (')' /= ) msuf
46 ln = splitOn "x" (tail marker)
47 len = read (ln!!0) :: Int
48 num = read (ln!!1) :: Int
49 (chunk, remainder) = splitAt len (tail suf)
50 dchunks = decompress2 chunk
51 mulDchunks = [(dl * num, ds) | (dl, ds) <- dchunks]
52 drest = decompress2 remainder
54 cLength :: [Chunk] -> Int
55 cLength = sum . map (clen)
56 where clen (n, t) = n * (length t)