diff --git a/2021/day03/day03.hs b/2021/day03/day03.hs index 4e3107b..7d88df1 100644 --- a/2021/day03/day03.hs +++ b/2021/day03/day03.hs @@ -1,13 +1,28 @@ +import Data.Bits +import Data.Char import Data.List -import Control.Lens -import Control.Arrow main :: IO () main = do input <- lines <$> readFile "input" - let counts = map ((\[x,y]->x>y) . map length . group . sort) $ transpose input - let (gamma,epsilon) = boolToDec *** boolToDec $ (id &&& map not) counts + let rating = take (length $ head input) $ transpose (map tails input) + let [gamma, epsilon] = [toDec $ map (commonBit f) rating | f <- [(<=), (>)]] print $ gamma * epsilon + let part2 = [genRating x input [] | x <- [(<=), (>)]] + print $ product $ map toDec part2 -boolToDec :: [Bool] -> Int -boolToDec = sum . imap (\x y->(2^x)*y) . reverse . map fromEnum +commonBit :: (Int -> Int -> Bool) -> [String] -> Int +commonBit f = + (\[x, y] -> fromEnum (x `f` y)) . + map (length) . group . sort . head . transpose + +genRating :: (Int -> Int -> Bool) -> [String] -> [Int] -> [Int] +genRating _ (x:[]) acc = acc ++ (map digitToInt x) +genRating f input acc = + genRating + f + (map tail $ filter (isPrefixOf (show $ commonBit f input)) input) + (acc ++ [commonBit f input]) + +toDec :: [Int] -> Int +toDec = sum . map (uncurry (*)) . zip (map bit [0 ..]) . reverse diff --git a/2021/day03/testinput b/2021/day03/testinput new file mode 100644 index 0000000..a6366a8 --- /dev/null +++ b/2021/day03/testinput @@ -0,0 +1,12 @@ +00100 +11110 +10110 +10111 +10101 +01111 +00111 +11100 +10000 +11001 +00010 +01010