summaryrefslogtreecommitdiff
path: root/2021/3.hs
blob: 98ca15c1258358f854aa608594ba408eef13abf1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module Main where

import Data.Bits
import Data.List

import Input


readBin :: [Bool] -> Int
readBin = sum . zipWith (*) (iterate (*2) 1) . reverse . map fromEnum

main :: IO ()
main = do
    inp <- map (map (== '1')) <$> getInput 3
    let n = length (head inp)
    let majority s = 2 * length (filter id s) > length s
    let gamma = readBin $ map majority $ transpose inp
        epsilon = complement gamma .&. (bit n - 1)
    print (gamma * epsilon)
    let filterstep _ _ [x] = [x]
        filterstep target idx cands = filter ((== target) . (!! idx)) cands
        perform targetrule = foldl' (\cs i -> filterstep (targetrule cs i) i cs) inp [0 .. n - 1]
        oxygen = perform $ \cs i -> 2 * length (filter id (map (!! i) cs)) >= length cs
        co2 = perform $ \cs i -> 2 * length (filter id (map (!! i) cs)) < length cs
    print (readBin (head oxygen) * readBin (head co2))