Day 8 done
[advent-of-code-19.git] / advent08 / src / advent08.hs
1 import Data.List
2 import Data.List.Split
3 import Data.Char
4 import Data.Ord
5 import Data.Function
6
7 main :: IO ()
8 main = do
9 text <- readFile "data/advent08.txt"
10 let digits = successfulParse text
11 let layers = chunksOf (imageWidth * imageHeight) digits
12 print $ part1 layers
13 putStrLn $ part2 layers
14
15
16 imageWidth = 25
17 imageHeight = 6
18
19 part1 layers = (count 1 target) * (count 2 target)
20 where target = minimumBy (comparing (count 0)) layers
21
22 part2 layers = unlines rows
23 where pixelLayers = transpose layers
24 pixels = map firstVisible pixelLayers
25 dPixels = map showPixel pixels
26 pixelRows = chunksOf imageWidth dPixels
27 rows = map concat pixelRows
28
29
30 firstVisible = head . dropWhile (== 2)
31
32 showPixel 0 = " "
33 showPixel 1 = "\x2588"
34
35
36 count n = length . filter (== n)
37
38 -- Count the number of times a predicate is true
39 -- (Taken from GHC API utility functions)
40
41 -- count :: (a -> Bool) -> [a] -> Int
42 -- count p = go 0
43 -- where go !n [] = n
44 -- go !n (x:xs) | p x = go (n+1) xs
45 -- | otherwise = go n xs
46
47
48 successfulParse :: String -> [Int]
49 successfulParse input = map digitToInt input