day 3
This commit is contained in:
parent
24da3016c5
commit
2564dad444
|
@ -1,13 +1,28 @@
|
||||||
|
import Data.Bits
|
||||||
|
import Data.Char
|
||||||
import Data.List
|
import Data.List
|
||||||
import Control.Lens
|
|
||||||
import Control.Arrow
|
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = do
|
main = do
|
||||||
input <- lines <$> readFile "input"
|
input <- lines <$> readFile "input"
|
||||||
let counts = map ((\[x,y]->x>y) . map length . group . sort) $ transpose input
|
let rating = take (length $ head input) $ transpose (map tails input)
|
||||||
let (gamma,epsilon) = boolToDec *** boolToDec $ (id &&& map not) counts
|
let [gamma, epsilon] = [toDec $ map (commonBit f) rating | f <- [(<=), (>)]]
|
||||||
print $ gamma * epsilon
|
print $ gamma * epsilon
|
||||||
|
let part2 = [genRating x input [] | x <- [(<=), (>)]]
|
||||||
|
print $ product $ map toDec part2
|
||||||
|
|
||||||
boolToDec :: [Bool] -> Int
|
commonBit :: (Int -> Int -> Bool) -> [String] -> Int
|
||||||
boolToDec = sum . imap (\x y->(2^x)*y) . reverse . map fromEnum
|
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
|
||||||
|
|
|
@ -0,0 +1,12 @@
|
||||||
|
00100
|
||||||
|
11110
|
||||||
|
10110
|
||||||
|
10111
|
||||||
|
10101
|
||||||
|
01111
|
||||||
|
00111
|
||||||
|
11100
|
||||||
|
10000
|
||||||
|
11001
|
||||||
|
00010
|
||||||
|
01010
|
Loading…
Reference in New Issue
Block a user