From 7a0450ec6ccc6cbb4100c84be9a0b7de8a7dde72 Mon Sep 17 00:00:00 2001 From: eriedaberrie Date: Mon, 2 Dec 2024 14:35:58 -0800 Subject: [PATCH] 2024 day 2: Haskell solution --- 2024/2/Main1.hs | 14 ++++++++++++++ 2024/2/Main2.hs | 22 ++++++++++++++++++++++ flake.lock | 6 +++--- flake.nix | 2 ++ 4 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 2024/2/Main1.hs create mode 100644 2024/2/Main2.hs diff --git a/2024/2/Main1.hs b/2024/2/Main1.hs new file mode 100644 index 0000000..4f72028 --- /dev/null +++ b/2024/2/Main1.hs @@ -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 " " diff --git a/2024/2/Main2.hs b/2024/2/Main2.hs new file mode 100644 index 0000000..146547d --- /dev/null +++ b/2024/2/Main2.hs @@ -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 " " diff --git a/flake.lock b/flake.lock index 726651e..c751a58 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1712963716, - "narHash": "sha256-WKm9CvgCldeIVvRz87iOMi8CFVB1apJlkUT4GGvA0iM=", + "lastModified": 1733015953, + "narHash": "sha256-t4BBVpwG9B4hLgc6GUBuj3cjU7lP/PJfpTHuSqE+crk=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "cfd6b5fc90b15709b780a5a1619695a88505a176", + "rev": "ac35b104800bff9028425fec3b6e8a41de2bbfff", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 6eda372..9723b50 100644 --- a/flake.nix +++ b/flake.nix @@ -27,6 +27,8 @@ split-sequence str ])) + pkgs.haskell-language-server + pkgs.stylish-haskell (pkgs.ghc.withPackages (p: with p; [ containers