My solutions to Advent of Code 2021
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

48 lines
998 B

  1. module Main where
  2. import Data.Bits (shift)
  3. main :: IO ()
  4. main = interact solution
  5. solution :: String -> String
  6. solution = show
  7. . (\(x,y) -> bits_to_number x * bits_to_number y)
  8. . (\x -> (o2 0 x, co2 0 x))
  9. . map (map (read . (:[])))
  10. . lines
  11. where
  12. bits_to_number :: [Int] -> Int
  13. bits_to_number = btn' . reverse
  14. where
  15. btn' :: [Int] -> Int
  16. btn' [] = 0
  17. btn' (a:r) = shift (btn' r) 1 + a
  18. count :: Eq a => Int -> a -> [[a]] -> Int
  19. count _ _ [] = 0
  20. count p e (a:r) = count p e r + if a !! p == e then 1 else 0
  21. o2 :: Int -> [[Int]] -> [Int]
  22. o2 _ [n] = n
  23. o2 n x = o2 next (filter (\e -> e !! n == mc) x)
  24. where
  25. next = n + 1
  26. c0 = count n 0 x
  27. c1 = count n 1 x
  28. mc
  29. | c0 <= c1 = 0
  30. | otherwise = 1
  31. co2 :: Int -> [[Int]] -> [Int]
  32. co2 _ [n] = n
  33. co2 n x = co2 next (filter (\e -> e !! n == lc) x)
  34. where
  35. next = n + 1
  36. c0 = count n 0 x
  37. c1 = count n 1 x
  38. lc
  39. | c0 <= c1 = 1
  40. | otherwise = 0