summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLaura Orvokki Kursula <lav@vampires.gay>2024-12-03 22:07:00 +0100
committerLaura Orvokki Kursula <lav@vampires.gay>2024-12-03 22:07:00 +0100
commit1c8ec4bd5515d90f75a5d98adbab810a81522890 (patch)
treea29f8cb19bd5daecdb7b946a8e236824b0ef2f52
parentadb8d55ccbc9aafa8949f1677e4784334ac695e7 (diff)
downloadaoc2024-1c8ec4bd5515d90f75a5d98adbab810a81522890.tar.gz
aoc2024-1c8ec4bd5515d90f75a5d98adbab810a81522890.zip
2-2
-rw-r--r--2-2.hs37
1 files changed, 37 insertions, 0 deletions
diff --git a/2-2.hs b/2-2.hs
new file mode 100644
index 0000000..0327f1e
--- /dev/null
+++ b/2-2.hs
@@ -0,0 +1,37 @@
+monotonic :: [Int] -> Bool
+monotonic xs = all (<0) xs || all (>0) xs
+
+gradual :: [Int] -> Bool
+gradual = all ((<= 3) . abs)
+
+differences :: [Int] -> [Int]
+differences (x:y:xs) = x-y : differences (y:xs)
+differences _ = []
+
+safe :: [Int] -> Bool
+safe xs = let ys = differences xs
+ in monotonic ys && gradual ys
+
+safe' :: [Int] -> Bool
+safe' = any safe . removals
+
+line :: String -> Bool
+line = safe' . map read . words
+
+count :: (a -> Bool) -> [a] -> Int
+count p = foldr f 0
+ where
+ f x y = if p x then succ y else y
+
+remove :: Int -> [a] -> [a]
+remove n xs = take n xs ++ drop (n+1) xs
+
+removals :: [a] -> [[a]]
+removals xs = map (flip remove xs) [0..length xs - 1]
+
+main :: IO ()
+main = do
+ s <- getContents
+ let ls = lines s
+ let xs = map line ls
+ print $ count id xs