Day 8: Space Image Format

https://adventofcode.com/2019/day/8


In [1]:
inputLine = head . lines <$> readFile "input/day08.txt"

In [2]:
imageSize = 25 * 6

Split the input into layers


In [3]:
import Data.List.Split
layers = chunksOf imageSize <$>  inputLine

Part 1

Count the number of 0, 1, 2 in a layer


In [4]:
count digit = length . filter (==digit)

In [5]:
count012 layer = map (($ layer). count) ['0'..'2']

Multiply number of 1 digits by number of 2 digits


In [6]:
product12 [_, n1, n2] = n1 * n2

Solution


In [7]:
product12 . minimum . map count012 <$> layers


1572

Part 2


In [8]:
mergeLayers :: String -> String -> String
mergeLayers = zipWith (\ a b -> if a == '2' then b else a)

In [9]:
solution = foldl1 mergeLayers

Verify given example


In [10]:
solution . chunksOf 4 $ "0222112222120000"


"0110"

Make it easier to read the result

Black pixels are replaced by # and white pixels by a space.


In [11]:
pixel :: Char -> Char
pixel '0' = ' '
pixel '1' = '#'

Solution


In [12]:
import Data.List (intercalate)
(intercalate "\n" . chunksOf 25 . map pixel . solution <$> layers) >>= putStrLn


#  # #   ##  # #### #### 
# #  #   ##  # #    #    
##    # # #### ###  ###  
# #    #  #  # #    #    
# #    #  #  # #    #    
#  #   #  #  # #    ####