This commit is contained in:
Gattix 2021-12-09 23:39:57 +01:00
parent 24da3016c5
commit 2564dad444
2 changed files with 33 additions and 6 deletions

@ -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

12
2021/day03/testinput Normal file

@ -0,0 +1,12 @@
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010