summaryrefslogtreecommitdiff
path: root/10-1.hs
diff options
context:
space:
mode:
authorLaura Orvokki Kursula <lav@vampires.gay>2024-12-10 12:56:58 +0100
committerLaura Orvokki Kursula <lav@vampires.gay>2024-12-10 13:03:24 +0100
commitcff3c9c15bce92c6697ef13be2485d6bcf7291ed (patch)
treef3826efc375f1eb79f1ec1f2d89f91740358b783 /10-1.hs
parent78b517b79ee7cc96e336342e8845ca032faa4a17 (diff)
downloadaoc2024-cff3c9c15bce92c6697ef13be2485d6bcf7291ed.tar.gz
aoc2024-cff3c9c15bce92c6697ef13be2485d6bcf7291ed.zip
10-1 with dynamic programming / memoization
Diffstat (limited to '10-1.hs')
-rw-r--r--10-1.hs14
1 files changed, 9 insertions, 5 deletions
diff --git a/10-1.hs b/10-1.hs
index afeff45..c11c017 100644
--- a/10-1.hs
+++ b/10-1.hs
@@ -1,3 +1,5 @@
+-- compile with -O2 to take advantage of memoization!
+
import Data.Array
import Data.List (nub)
@@ -5,6 +7,11 @@ data Pos = Pos Int Int deriving (Eq,Ix,Ord,Show)
type Map = Array Pos Int
+type Memo = Array Pos [Pos]
+
+memo :: Map -> Memo
+memo m = array (bounds m) [ (p, reachable m p) | p <- indices m ]
+
step :: Map -> Pos -> [Pos]
step m p@(Pos x y) = filter ((== 1) . subtract (m ! p) . (m !))
. filter (`elem` indices m)
@@ -22,10 +29,7 @@ height = length
reachable :: Map -> Pos -> [Pos]
reachable m p | m ! p == 9 = [p]
- | otherwise = concatMap (reachable m) $ step m p
-
-score :: Map -> Pos -> Int
-score m = length . nub . reachable m
+ | otherwise = nub . concatMap (memo m !) $ step m p
trailheads :: Map -> [Pos]
trailheads = map fst . filter ((== 0) . snd) . assocs
@@ -38,4 +42,4 @@ parse ls = listArray
main :: IO ()
main = do
m <- parse . lines <$> getContents
- print . sum . map (score m) . trailheads $ m
+ print . sum . map (length . (memo m !)) . trailheads $ m