This commit is contained in:
opfez 2021-12-04 00:13:26 +01:00
parent f5f0684acd
commit 88e515c82b
3 changed files with 1063 additions and 0 deletions

28
day3/first.hs Normal file
View File

@ -0,0 +1,28 @@
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
gamma :: [String] -> Integer
gamma = binaryToInt . map (mostCommon '1' '0') . transpose
epsilon :: [String] -> Integer
epsilon = binaryToInt . map (leastCommon '1' '0') . transpose
main = interact $ show . solution . words
where solution bitstrings = gamma bitstrings * epsilon bitstrings

1000
day3/input Normal file

File diff suppressed because it is too large Load Diff

35
day3/second.hs Normal file
View File

@ -0,0 +1,35 @@
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