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.

64 lines
1.6 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. module Main where
  2. import Data.List.Split (chunksOf, splitOn)
  3. import Debug.Trace (traceShowId)
  4. import Data.List (transpose)
  5. main :: IO ()
  6. main = interact solution
  7. type Board = [(Bool, Int)]
  8. second :: (b -> c) -> (a, b) -> (a, c)
  9. second f (a, b) = (a, f b)
  10. second2 :: (a -> b -> c) -> (a, b) -> (a, c)
  11. second2 f (a, b) = (a, f a b)
  12. first :: (a -> c) -> (a, b) -> (c, b)
  13. first f (a, b) = (f a, b)
  14. solution :: String -> String
  15. solution = show
  16. . second2 applydraws
  17. . second ( chunksOf 25
  18. . zip (repeat False)
  19. . map (read :: String -> Int)
  20. . concatMap words
  21. )
  22. . first ( map (read :: String -> Int)
  23. . splitOn ","
  24. )
  25. . (\x -> (head x, tail x))
  26. . lines
  27. select :: Int -> Board -> Board
  28. select n = map (\(d, p) -> ((n == p) || d, p))
  29. hasWon :: Board -> Bool
  30. hasWon b = any and r || any and (transpose r)
  31. where r = chunksOf 5 (map fst b)
  32. score :: Int -> Board -> Int
  33. score lastn b = lastn * boardleft b
  34. where boardleft = sum . map snd . filter (not . fst)
  35. applydraw :: Int -> [Board] -> [Board]
  36. applydraw n = map (select n)
  37. applydraws ::[Int] -> [Board] -> [(Int, [Board])]
  38. applydraws [] _ = []
  39. applydraws (n:ns) b = (n, nb) : applydraws ns nb
  40. where
  41. nb = applydraw n b
  42. getWinning :: [[Board]] -- ^ Mapped boards
  43. -> Board
  44. getWinning [] = error "WTF"
  45. getWinning (bs:r) = if any hasWon bs then getWinning' bs else getWinning r
  46. where
  47. getWinning' :: [Board] -> Board
  48. getWinning' (b:bs)
  49. | hasWon b = b
  50. | otherwise = getWinning' bs
  51. getWinning' [] = error "Wtf"