|
|
@@ -0,0 +1,40 @@ |
|
|
|
main :: IO () |
|
|
|
main = do |
|
|
|
raw <- readFile "day9.txt" |
|
|
|
let nums = (map read $ lines raw) :: [Int] |
|
|
|
ansA = solveA nums |
|
|
|
ansB = solveB ansA nums |
|
|
|
in do |
|
|
|
putStrLn $ "day9a: " ++ (show ansA) |
|
|
|
putStrLn $ "day9b: " ++ (show ansB) |
|
|
|
|
|
|
|
solveA :: [Int] -> Int |
|
|
|
solveA nums = runWindow' (take 25 nums) (drop 25 nums) |
|
|
|
|
|
|
|
solveB :: Int -> [Int] -> Int |
|
|
|
solveB t nums = (maximum ans) + (minimum ans) |
|
|
|
where |
|
|
|
ans = testRuns t nums |
|
|
|
|
|
|
|
runWindow' :: [Int] -> [Int] -> Int |
|
|
|
runWindow' _ [] = error "reached end of stream" |
|
|
|
runWindow' win (n:ns) = |
|
|
|
if n `elem` ws |
|
|
|
then runWindow' ((tail win) ++ [n]) ns |
|
|
|
else n |
|
|
|
where |
|
|
|
ws = [ x+y | x <- ls, y <- ls, x /= y ] |
|
|
|
ls = filter (<= (n - (minimum win))) win |
|
|
|
|
|
|
|
findRun :: Int -> [Int] -> Int -> [Int] -> Maybe [Int] |
|
|
|
findRun _ _ _ [] = Nothing |
|
|
|
findRun t a r (l:ls) |
|
|
|
| r + l == t = Just (l:a) |
|
|
|
| r + l > t = Nothing |
|
|
|
| otherwise = findRun t (l:a) (r + l) ls |
|
|
|
|
|
|
|
testRuns :: Int -> [Int] -> [Int] |
|
|
|
testRuns _ [] = error "no answer" |
|
|
|
testRuns t ls = case (findRun t [] 0 ls) of |
|
|
|
Nothing -> testRuns t (tail ls) |
|
|
|
Just x -> x |