aboutsummaryrefslogtreecommitdiff
path: root/2020/09-Encoding_Error/first.hs
diff options
context:
space:
mode:
authorJulien Dessaux2023-03-17 23:36:44 +0100
committerJulien Dessaux2023-03-17 23:36:44 +0100
commitd7756f372421bdc4b4239f31503dda1b9d1fe275 (patch)
treebf88dbadaef2bd0d62ba302ad273365ed413c8c3 /2020/09-Encoding_Error/first.hs
parent2020-08 in haskell (diff)
downloadadvent-of-code-d7756f372421bdc4b4239f31503dda1b9d1fe275.tar.gz
advent-of-code-d7756f372421bdc4b4239f31503dda1b9d1fe275.tar.bz2
advent-of-code-d7756f372421bdc4b4239f31503dda1b9d1fe275.zip
2020-09 in haskell
Diffstat (limited to '')
-rw-r--r--2020/09-Encoding_Error/first.hs31
1 files changed, 31 insertions, 0 deletions
diff --git a/2020/09-Encoding_Error/first.hs b/2020/09-Encoding_Error/first.hs
new file mode 100644
index 0000000..400c15f
--- /dev/null
+++ b/2020/09-Encoding_Error/first.hs
@@ -0,0 +1,31 @@
+module Main (main) where
+import Control.Monad (when)
+import Data.List (foldl')
+import System.Exit (die)
+
+exampleExpectedOutput = 127
+
+parseInput :: String -> IO [Int]
+parseInput filename = do
+ input <- readFile filename
+ return $ map read $ lines input
+
+validate :: [Int] -> Int -> Bool
+validate list n = processInput list
+ where
+ processInput :: [Int] -> Bool
+ processInput (_:[]) = False
+ processInput (x:xs) = (foldl' (\acc i -> acc || (x + i == n && x /= i)) False xs) || processInput xs
+
+compute :: Int -> [Int] -> Int
+compute len list
+ | validate (take len list) (list !! len) = compute len $ tail list
+ | otherwise = list !! len
+
+main :: IO ()
+main = do
+ example <- parseInput "example"
+ let exampleOutput = compute 5 example
+ when (exampleOutput /= exampleExpectedOutput) (die $ "example failed: got " ++ show exampleOutput ++ " instead of " ++ show exampleExpectedOutput)
+ input <- parseInput "input"
+ print $ compute 25 input