Add Day 5, Puzzle 2 solution

This commit is contained in:
Daniele Fucini
2025-12-05 12:55:01 +01:00
parent 8828c9fe7f
commit 934a2d437f
3 changed files with 24 additions and 2 deletions

View File

@@ -6,5 +6,5 @@
|02 |★ ★ |08 | | |02 |★ ★ |08 | |
|03 |★ ★ |09 | | |03 |★ ★ |09 | |
|04 |★ ★ |10 | | |04 |★ ★ |10 | |
|05 |★ |11 | | |05 |★ |11 | |
|06 | |12 | | |06 | |12 | |

View File

@@ -2,9 +2,11 @@
module Day05 module Day05
( day05_1, ( day05_1,
day05_2,
) )
where where
import Data.List (sortOn)
import Data.List.Split (splitOn) import Data.List.Split (splitOn)
getRange :: String -> (Int, Int) getRange :: String -> (Int, Int)
@@ -20,6 +22,14 @@ isFresh ingredient (r : rs)
| ingredient >= fst r && ingredient <= snd r = True | ingredient >= fst r && ingredient <= snd r = True
| otherwise = isFresh ingredient rs | otherwise = isFresh ingredient rs
countIngredients :: [(Int, Int)] -> Int -> Int
countIngredients [] tot = tot
countIngredients [r] tot = snd r - fst r + 1 + tot
countIngredients (r : s : rs) tot
| snd r >= snd s = countIngredients (r : rs) tot
| snd r >= fst s = countIngredients ((fst r, fst s - 1) : s : rs) tot
| otherwise = countIngredients (s : rs) (snd r - fst r + 1 + tot)
parseInput :: IO [String] parseInput :: IO [String]
parseInput = do parseInput = do
lines <$> readFile "input/day5.txt" lines <$> readFile "input/day5.txt"
@@ -32,3 +42,12 @@ day05_1 = do
putStrLn $ putStrLn $
"Day 5, Puzzle 1 solution: " "Day 5, Puzzle 1 solution: "
++ show (length freshIngredients) ++ show (length freshIngredients)
day05_2 :: IO ()
day05_2 = do
input <- parseInput
let ranges = sortOn fst . sortOn snd . map getRange $ takeWhile (/= "") input
result = countIngredients ranges 0
putStrLn $
"Day 5, Puzzle 2 solution: "
++ show result

View File

@@ -4,7 +4,7 @@ import Day01 (day01_1, day01_2)
import Day02 (day02_1, day02_2) import Day02 (day02_1, day02_2)
import Day03 (day03_1, day03_2) import Day03 (day03_1, day03_2)
import Day04 (day04_1, day04_2) import Day04 (day04_1, day04_2)
import Day05 (day05_1) import Day05 (day05_1, day05_2)
import System.Environment (getArgs) import System.Environment (getArgs)
main :: IO () main :: IO ()
@@ -32,8 +32,10 @@ main = do
day04_1 day04_1
day04_2 day04_2
"5" : "1" : _ -> day05_1 "5" : "1" : _ -> day05_1
"5" : "2" : _ -> day05_2
"5" : _ -> do "5" : _ -> do
day05_1 day05_1
day05_2
"all" : _ -> do "all" : _ -> do
day01_1 day01_1
day01_2 day01_2
@@ -44,4 +46,5 @@ main = do
day04_1 day04_1
day04_2 day04_2
day05_1 day05_1
day05_2
_ -> error "Not implemented" _ -> error "Not implemented"