Add Day 4, Puzzle 2 solution
This commit is contained in:
@@ -5,6 +5,6 @@
|
||||
|01 |★ ★ |07 | |
|
||||
|02 |★ ★ |08 | |
|
||||
|03 |★ ★ |09 | |
|
||||
|04 |★ |10 | |
|
||||
|04 |★ ★ |10 | |
|
||||
|05 | |11 | |
|
||||
|06 | |12 | |
|
||||
|
||||
32
src/Day04.hs
32
src/Day04.hs
@@ -2,6 +2,7 @@
|
||||
|
||||
module Day04
|
||||
( day04_1,
|
||||
day04_2,
|
||||
)
|
||||
where
|
||||
|
||||
@@ -38,11 +39,32 @@ isAccessible grid position
|
||||
| otherwise = getAdjacent grid position < 4
|
||||
|
||||
countAccessible :: Grid -> Int
|
||||
countAccessible grid = let w = length $ head grid
|
||||
countAccessible grid =
|
||||
let w = length $ head grid
|
||||
h = length grid
|
||||
positions = [(x, y) | x <- [0 .. w - 1], y <- [0 .. h - 1]]
|
||||
in length . filter id $ map (isAccessible grid) positions
|
||||
|
||||
removePaper :: Grid -> Position -> Grid
|
||||
removePaper grid position = take (snd position) grid ++ newRow ++ drop (snd position + 1) grid
|
||||
where
|
||||
newRow = [take (fst position) (grid !! snd position) ++ ['.'] ++ drop (fst position + 1) (grid !! snd position)]
|
||||
|
||||
removeAccessible :: Grid -> Grid
|
||||
removeAccessible grid =
|
||||
let w = length $ head grid
|
||||
h = length grid
|
||||
positions = filter (isAccessible grid) [(x, y) | x <- [0 .. w - 1], y <- [0 .. h - 1]]
|
||||
in removeRecursive grid positions
|
||||
where
|
||||
removeRecursive grid' [] = grid'
|
||||
removeRecursive grid' (p : ps) = removeRecursive (removePaper grid' p) ps
|
||||
|
||||
countAccessibleRecursive :: Grid -> Int -> Int
|
||||
countAccessibleRecursive grid tot
|
||||
| countAccessible grid == 0 = tot
|
||||
| otherwise = countAccessibleRecursive (removeAccessible grid) (tot + countAccessible grid)
|
||||
|
||||
parseInput :: IO [String]
|
||||
parseInput = lines <$> readFile "input/day4.txt"
|
||||
|
||||
@@ -53,3 +75,11 @@ day04_1 = do
|
||||
putStrLn $
|
||||
"Day 4, Puzzle 1 solution: "
|
||||
++ show result
|
||||
|
||||
day04_2 :: IO ()
|
||||
day04_2 = do
|
||||
grid <- parseInput
|
||||
let result = countAccessibleRecursive grid 0
|
||||
putStrLn $
|
||||
"Day 4, Puzzle 2 solution: "
|
||||
++ show result
|
||||
|
||||
@@ -3,7 +3,7 @@ module Main (main) where
|
||||
import Day01 (day01_1, day01_2)
|
||||
import Day02 (day02_1, day02_2)
|
||||
import Day03 (day03_1, day03_2)
|
||||
import Day04 (day04_1)
|
||||
import Day04 (day04_1, day04_2)
|
||||
import System.Environment (getArgs)
|
||||
|
||||
main :: IO ()
|
||||
@@ -26,8 +26,10 @@ main = do
|
||||
day03_1
|
||||
day03_2
|
||||
"4" : "1" : _ -> day04_1
|
||||
"4" : "2" : _ -> day04_2
|
||||
"4" : _ -> do
|
||||
day04_1
|
||||
day04_2
|
||||
"all" : _ -> do
|
||||
day01_1
|
||||
day01_2
|
||||
@@ -36,4 +38,5 @@ main = do
|
||||
day03_1
|
||||
day03_2
|
||||
day04_1
|
||||
day04_2
|
||||
_ -> error "Not implemented"
|
||||
|
||||
Reference in New Issue
Block a user