36 lines
1.1 KiB
Haskell
36 lines
1.1 KiB
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
|
|
|
|
filterNums :: Eq a => ([a] -> a) -> [[a]] -> [a]
|
|
filterNums test ns = aux 0 ns
|
|
where aux _ [final] = final
|
|
aux pos ns =
|
|
aux (pos + 1) $ filter ((==) needle . head . drop pos) ns
|
|
where needle = test $ map head $ map (drop pos) ns
|
|
|
|
oxygen :: [String] -> Integer
|
|
oxygen = binaryToInt . filterNums (mostCommon '1' '0')
|
|
|
|
co2 :: [String] -> Integer
|
|
co2 = binaryToInt . filterNums (leastCommon '1' '0')
|
|
|
|
main = interact $ show . solution . words
|
|
where solution bitstrings = oxygen bitstrings * co2 bitstrings
|