Add Day 2 solutions

This commit is contained in:
Daniele Fucini
2025-12-02 18:32:29 +01:00
parent fbc08a2e45
commit 32687cdfdd
4 changed files with 57 additions and 1 deletions

46
src/Day02.hs Normal file
View File

@@ -0,0 +1,46 @@
module Day02
( day02_1,
day02_2
)
where
import Data.List (isInfixOf)
import Data.List.Split (splitOn)
sumInvalid :: [Int] -> Int
sumInvalid = foldl addInvalid 0
where
addInvalid acc n
| odd (length (show n)) = acc
| let l2 = length (show n) `div` 2, take l2 (show n) == drop l2 (show n) = acc + n
| otherwise = acc
sumInvalid' :: [Int] -> Int
sumInvalid' = foldl addInvalid 0
where addInvalid acc n
| let s = drop 1 $ show n ++ show n, show n `isInfixOf` take (length s - 1) s = acc + n
| otherwise = acc
getRange :: String -> [Int]
getRange r = [read (takeWhile (/= '-') r)..read $ drop 1 (dropWhile (/= '-') r)]
parseInput :: IO [Int]
parseInput = do
concatMap getRange . splitOn "," <$> readFile "input/day2.txt"
day02_1 :: IO ()
day02_1 = do
values <- parseInput
let result = sumInvalid values
putStrLn $
"Day 2, Puzzle 1 solution: "
++ show result
day02_2 :: IO ()
day02_2 = do
values <- parseInput
let result = sumInvalid' values
putStrLn $
"Day 2, Puzzle 1 solution: "
++ show result