aoc2021/Day3.hs

35 lines
1.0 KiB
Haskell
Raw Normal View History

2021-12-03 17:44:53 +00:00
module Day3 where
import System.IO (openFile, IOMode (ReadMode), hClose, hGetContents)
import Data.List ( maximumBy, minimumBy, group, sort )
import Data.Function (on)
import Data.Char (digitToInt)
column :: String -> Int -> String
column str i = map (!! i) $ lines str
columns :: String -> Int
columns str = maximum $ map length $ lines str
mostCommon :: String -> Char
mostCommon str = head . maximumBy (compare `on` length) . group $ sort str
leastCommon :: String -> Char
leastCommon str = head . minimumBy (compare `on` length) . group $ sort str
binaryToDecimal :: Int -> Int
binaryToDecimal = foldl1 ((+) . (2 *)) . map digitToInt . show
main :: IO ()
main = do
input <- openFile "inputs/3.txt" ReadMode
contents <- hGetContents input
let gamma = mostCommon . column contents <$> [0..(columns contents - 1)]
let epsilon = leastCommon . column contents <$> [0..(columns contents - 1)]
let energy = product (binaryToDecimal . read <$> [gamma, epsilon] :: [Int])
print energy
hClose input