mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
Implement 2025 day 7 part 1 in Haskell
This commit is contained in:
3
2025/day07/.gitignore
vendored
Normal file
3
2025/day07/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
solve
|
||||
*.o
|
||||
*.hi
|
||||
14
2025/day07/Makefile
Normal file
14
2025/day07/Makefile
Normal file
@@ -0,0 +1,14 @@
|
||||
.PHONY: all clean test
|
||||
|
||||
all: solve
|
||||
|
||||
test: solve
|
||||
./solve sample.txt
|
||||
|
||||
solve: solve.hs
|
||||
ghc -dynamic -O -o $@ $^
|
||||
|
||||
clean:
|
||||
$(RM) solve
|
||||
$(RM) *.o
|
||||
$(RM) *.hi
|
||||
16
2025/day07/sample.txt
Normal file
16
2025/day07/sample.txt
Normal file
@@ -0,0 +1,16 @@
|
||||
.......S.......
|
||||
...............
|
||||
.......^.......
|
||||
...............
|
||||
......^.^......
|
||||
...............
|
||||
.....^.^.^.....
|
||||
...............
|
||||
....^.^...^....
|
||||
...............
|
||||
...^.^...^.^...
|
||||
...............
|
||||
..^...^.....^..
|
||||
...............
|
||||
.^.^.^.^.^...^.
|
||||
...............
|
||||
38
2025/day07/solve.hs
Normal file
38
2025/day07/solve.hs
Normal file
@@ -0,0 +1,38 @@
|
||||
import Basement.Compat.IsList qualified as Set
|
||||
import Data.Array
|
||||
import Data.List
|
||||
import Data.Maybe
|
||||
import Data.Set
|
||||
import System.Environment
|
||||
import System.Exit
|
||||
|
||||
main = getArgs >>= parse >>= (print . solve . lines)
|
||||
|
||||
findStartingPoint line = fromJust (elemIndex 'S' line)
|
||||
|
||||
solve lines = simulate (tail lines) 0 (Data.Set.singleton (findStartingPoint (head lines)))
|
||||
|
||||
stringToArray :: [Char] -> Array Int Char
|
||||
stringToArray s = listArray (0, length s - 1) s
|
||||
|
||||
checkHit :: Array Int Char -> Int -> [Int]
|
||||
checkHit line idx = case line ! idx of
|
||||
'^' -> (idx - 1) : [idx + 1]
|
||||
_ -> [idx]
|
||||
|
||||
simulate :: [[Char]] -> Int -> Set Int -> Int
|
||||
simulate [] count active = count
|
||||
simulate lines count active =
|
||||
let arr = stringToArray (head lines)
|
||||
followUp = Data.Set.fromList $ concatMap (checkHit arr) (Set.toList active)
|
||||
hits = length (Data.Set.filter (\i -> arr ! i == '^') active)
|
||||
remainder = tail lines
|
||||
in simulate remainder (hits + count) followUp
|
||||
|
||||
parse ["-h"] = usage >> exitSuccess
|
||||
parse [] = usage >> die usageStr
|
||||
parse fs = concat `fmap` mapM readFile fs
|
||||
|
||||
usageStr = "Usage: solve [-vh] [file ..]"
|
||||
|
||||
usage = putStrLn usageStr
|
||||
Reference in New Issue
Block a user