2024 day 2: Haskell solution

This commit is contained in:
eriedaberrie 2024-12-02 14:35:58 -08:00
parent 40b7af94ca
commit 7a0450ec6c
4 changed files with 41 additions and 3 deletions

14
2024/2/Main1.hs Normal file
View file

@ -0,0 +1,14 @@
import Data.List.Split (splitOn)
lineSafe :: [Int] -> Bool
lineSafe [] = True
lineSafe l@(_:xs) = (all (> 0) diffs || all (< 0) diffs) && all validItem diffs
where
diffs = zipWith (-) xs l
validItem x = x /= 0 && abs x <= 3
main :: IO ()
main = print . length . filter testLine . lines =<< readFile "data.txt"
where
testLine = lineSafe . map read . splitOn " "

22
2024/2/Main2.hs Normal file
View file

@ -0,0 +1,22 @@
import Data.List.Split (splitOn)
lineSafe' :: [Int] -> Bool
lineSafe' [] = True
lineSafe'
l@(_:xs) = (all (> 0) diffs || all (< 0) diffs) && all validItem diffs
where
diffs = zipWith (-) xs l
validItem x = x /= 0 && abs x <= 3
allRemoved :: [a] -> [[a]]
allRemoved [] = []
allRemoved (x:xs) = xs:map (x:) (allRemoved xs)
lineSafe :: [Int] -> Bool
lineSafe = any lineSafe' . allRemoved
main :: IO ()
main = print . length . filter testLine . lines =<< readFile "data.txt"
where
testLine = lineSafe . map read . splitOn " "

View file

@ -2,11 +2,11 @@
"nodes": { "nodes": {
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1712963716, "lastModified": 1733015953,
"narHash": "sha256-WKm9CvgCldeIVvRz87iOMi8CFVB1apJlkUT4GGvA0iM=", "narHash": "sha256-t4BBVpwG9B4hLgc6GUBuj3cjU7lP/PJfpTHuSqE+crk=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "cfd6b5fc90b15709b780a5a1619695a88505a176", "rev": "ac35b104800bff9028425fec3b6e8a41de2bbfff",
"type": "github" "type": "github"
}, },
"original": { "original": {

View file

@ -27,6 +27,8 @@
split-sequence split-sequence
str str
])) ]))
pkgs.haskell-language-server
pkgs.stylish-haskell
(pkgs.ghc.withPackages (p: (pkgs.ghc.withPackages (p:
with p; [ with p; [
containers containers