Tidying, especially the parser
[advent-of-code-16.git] / adventofcode16 / app / advent22showgrid.hs
1 {-# LANGUAGE DeriveGeneric #-}
2
3 module Main(main) where
4
5 import GHC.Generics (Generic)
6 import Text.Parsec
7 import Text.ParserCombinators.Parsec.Number
8 import Data.Maybe (catMaybes, fromJust)
9 import Data.List (find, delete, sort, sortOn, reverse)
10
11 data Node = Node { x :: Int
12 , y :: Int
13 , size :: Int
14 , used :: Int
15 , available :: Int
16 , use_pc :: Int
17 } deriving (Show, Eq, Ord)
18
19
20 testGrid = "\
21 \Filesystem Size Used Avail Use%\n\
22 \/dev/grid/node-x0-y0 10T 8T 2T 80%\n\
23 \/dev/grid/node-x0-y1 11T 6T 5T 54%\n\
24 \/dev/grid/node-x0-y2 32T 28T 4T 87%\n\
25 \/dev/grid/node-x1-y0 9T 7T 2T 77%\n\
26 \/dev/grid/node-x1-y1 8T 0T 8T 0%\n\
27 \/dev/grid/node-x1-y2 11T 7T 4T 63%\n\
28 \/dev/grid/node-x2-y0 10T 6T 4T 60%\n\
29 \/dev/grid/node-x2-y1 9T 8T 1T 88%\n\
30 \/dev/grid/node-x2-y2 9T 6T 3T 66%\n\
31 \"
32
33 main :: IO ()
34 main = do
35 text <- readFile "data/advent22.txt"
36 let sizes = successfulParse $ parseFile text
37 let maxX = maximum $ map (\n -> x n) sizes
38 let maxY = maximum $ map (\n -> y n) sizes
39 putStrLn $ unlines $ map (showRow maxX sizes) [0..(maxY-1)]
40
41
42 showRow maxX sizes r = map (charOf) row
43 where row = sortOn (\c -> x c) $ filter (\c -> y c == r) sizes
44 charOf c = if (used c) == 0
45 then '+'
46 else if (used c) > 100
47 then '#'
48 else '_'
49
50
51
52
53 duFile = duLine `sepEndBy` newline
54 -- duLine = (optionMaybe nodeL)
55
56 duLine = (nodeL >>= return . Just) <|> (headerL >> return Nothing)
57
58 headerL = (many (noneOf "\r\n"))
59
60 nodeL = nodeify <$> (string "/dev/grid/node-x" *> int)
61 <*> (string "-y" *> int)
62 <*> (spaces *> int <* string "T")
63 <*> (spaces *> int <* string "T")
64 <*> (spaces *> int <* string "T")
65 <*> (spaces *> int <* string "%")
66 where nodeify x y size used available use_pc =
67 Node {x=x, y=y, size=size, used=used, available=available, use_pc=use_pc}
68
69 parseFile :: String -> Either ParseError [Maybe Node]
70 parseFile input = parse duFile "(unknown)" input
71
72 parseLine :: String -> Either ParseError (Maybe Node)
73 parseLine input = parse duLine "(unknown)" input
74
75 successfulParse :: Either ParseError [Maybe a] -> [a]
76 successfulParse (Left _) = []
77 successfulParse (Right a) = catMaybes a