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.

41 lines
1.1KB

  1. main :: IO ()
  2. main = do
  3. raw <- readFile "day9.txt"
  4. let nums = (map read $ lines raw) :: [Int]
  5. ansA = solveA nums
  6. ansB = solveB ansA nums
  7. in do
  8. putStrLn $ "day9a: " ++ (show ansA)
  9. putStrLn $ "day9b: " ++ (show ansB)
  10. solveA :: [Int] -> Int
  11. solveA nums = runWindow' (take 25 nums) (drop 25 nums)
  12. solveB :: Int -> [Int] -> Int
  13. solveB t nums = (maximum ans) + (minimum ans)
  14. where
  15. ans = testRuns t nums
  16. runWindow' :: [Int] -> [Int] -> Int
  17. runWindow' _ [] = error "reached end of stream"
  18. runWindow' win (n:ns) =
  19. if n `elem` ws
  20. then runWindow' ((tail win) ++ [n]) ns
  21. else n
  22. where
  23. ws = [ x+y | x <- ls, y <- ls, x /= y ]
  24. ls = filter (<= (n - (minimum win))) win
  25. findRun :: Int -> [Int] -> Int -> [Int] -> Maybe [Int]
  26. findRun _ _ _ [] = Nothing
  27. findRun t a r (l:ls)
  28. | r + l == t = Just (l:a)
  29. | r + l > t = Nothing
  30. | otherwise = findRun t (l:a) (r + l) ls
  31. testRuns :: Int -> [Int] -> [Int]
  32. testRuns _ [] = error "no answer"
  33. testRuns t ls = case (findRun t [] 0 ls) of
  34. Nothing -> testRuns t (tail ls)
  35. Just x -> x