day3: Complete first puzzle

This commit is contained in:
Tristan Daniël Maat 2021-12-03 23:08:59 +00:00
parent 31305e22f8
commit b13c001634
Signed by: tlater
GPG key ID: 49670FD774E43268
2 changed files with 1059 additions and 0 deletions

59
3/diagnosticReader.hs Normal file
View file

@ -0,0 +1,59 @@
import Control.Exception (assert)
import Data.Bits (bit)
import Data.Char (digitToInt)
import Data.List (group, maximumBy, minimumBy, sort,
transpose)
import Data.Ord (comparing)
main :: IO ()
main = do
diagnostics <- getContents
putStrLn (solution1 diagnostics)
solution1 :: String -> String
solution1 diagnostics = show (calcGamma * calcEpsilon)
where
calcGamma = listToBit (map most (parseDiagnostics diagnostics))
calcEpsilon = listToBit (map least (parseDiagnostics diagnostics))
parseDiagnostics :: String -> [[Int]]
parseDiagnostics diagnostics = map (map digitToInt) (transpose (lines diagnostics))
most :: [Int] -> Int
most = head . (maximumBy (comparing length)) . group . sort
least :: [Int] -> Int
least = head . (minimumBy (comparing length)) . group . sort
listToBit :: [Int] -> Int
listToBit list = foldr (\b acc -> (acc + toBit b)) 0 (enumerate (reverse list))
where
-- Takes a location and value to converts it to the appropriate
-- integer.
toBit :: (Int, Int) -> Int
toBit (i, b) = if b == 1
then bit i
else 0
enumerate :: [a] -> [(Int, a)]
enumerate = zip [0..]
-- Tests
testInput1 :: String
testInput1 = unlines [
"00100",
"11110",
"10110",
"10111",
"10101",
"01111",
"00111",
"11100",
"10000",
"11001",
"00010",
"01010"
]
test1 :: String
test1 = assert ((solution1 testInput1) == "198") "success"

1000
3/input.txt Normal file

File diff suppressed because it is too large Load diff