aoc-2021/day3/first.hs

29 lines
843 B
Haskell

import Data.List
binaryToInt :: String -> Integer
binaryToInt bits = aux 0 0 $ reverse bits
where aux expt acc [] = acc
aux expt acc ('1':bits) = aux (expt + 1) (acc + 2^expt) bits
aux expt acc ('0':bits) = aux (expt + 1) acc bits
mostCommon :: Eq a => a -> a -> [a] -> a
mostCommon x y elems
| xs <= ys = y
| ys < xs = x
where xs = lenMap x
ys = lenMap y
lenMap a = length $ filter id $ map (== a) elems
leastCommon x y elems
| mostCommon x y elems == x = y
| mostCommon x y elems == y = x
gamma :: [String] -> Integer
gamma = binaryToInt . map (mostCommon '1' '0') . transpose
epsilon :: [String] -> Integer
epsilon = binaryToInt . map (leastCommon '1' '0') . transpose
main = interact $ show . solution . words
where solution bitstrings = gamma bitstrings * epsilon bitstrings