Add 2020 day 9

This commit is contained in:
Xavier Morel
2020-12-09 17:53:53 +01:00
parent a37ce2930d
commit 033691fd38
3 changed files with 1041 additions and 0 deletions

1000
haskellAoC/inputs/2020/09 Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
module Y2020.Day09 (y20day09) where
import Data.Maybe
hasSumInList :: Int -> [Int] -> Bool
hasSumInList _ [] = False
hasSumInList nb (x:xs)
| (nb - x) `elem` xs = True
| otherwise = hasSumInList nb xs
walkTilInvalid :: [Int] -> [Int] -> Int
walkTilInvalid (cur:next) last25
| hasSumInList cur last25 = walkTilInvalid next (cur:(init last25))
| otherwise = cur
walkTilInvalid _ _ = -1
getSum :: [Int] -> Int -> Maybe [Int]
getSum [] _ = Nothing
getSum (y:ys) t
| y > t = Nothing
| y == t = Just [y]
| otherwise = fmap (\zs -> y:zs) (getSum ys (t-y))
findContiguousSum :: [Int] -> Int -> [Int]
findContiguousSum (x:xs) target
| x >= target = findContiguousSum xs target
| isJust sumStartingThere = fromJust sumStartingThere
| otherwise = findContiguousSum xs target
where sumStartingThere = getSum xs target
y20day09 :: [String] -> (String, String)
y20day09 input = (part1, part2)
where part1 = show $ firstInvalid
part2 = show $ (minimum contiguousSum + maximum contiguousSum)
input' = map read $ input :: [Int]
preamble = reverse $ take 25 $ input'
rest = drop 25 $ input'
firstInvalid = walkTilInvalid rest preamble
contiguousSum = findContiguousSum input' firstInvalid

View File

@@ -8,6 +8,7 @@ import Y2020.Day05
import Y2020.Day06
import Y2020.Day07
import Y2020.Day08
import Y2020.Day09
year2020 :: String -> [String] -> (String, String)
year2020 "01" = y20day01
@@ -18,3 +19,4 @@ year2020 "05" = y20day05
year2020 "06" = y20day06
year2020 "07" = y20day07
year2020 "08" = y20day08
year2020 "09" = y20day09