## ~rootmos/AoC

cdf2f06537105804490f2f1c6d3201ddda9074e4 — Gustav Behm 1 year, 3 months ago
```Add solution to AoC 2022 #14b
```
```1 files changed, 20 insertions(+), 13 deletions(-)

M 2022/14.hs
```
`M 2022/14.hs => 2022/14.hs +20 -13`
```@@ 57,8 57,11 @@ isBlocked Air = False

type Cave s = STArray s (Int, Int) Point

-initialCave :: [ Line ] -> ST s (Cave s)
-initialCave ls = STArray.newArray (bounds ls) Air >>= flip f ls
+initialCave :: Bool -> [ Line ] -> ST s (Cave s)
+initialCave True ls = initialCave False (floor:ls)
+  where floor = let ((_, _), (_, y)) = bounds ls in
+                [ Horizontal (500-2*y,500+2*y) (y+2) ]
+initialCave False ls = STArray.newArray (bounds ls) Air >>= flip f ls
where f c [] = return c
f c (l:ls) = g c l >> f c ls
g c [] = return ()

@@ 84,8 87,15 @@ drawUnsafe ls = unsafePerformIO \$ do
putStrLn ""
sequence_ \$ fmap putStrLn ls

+isFull :: Cave s -> ST s Bool
+isFull c = do
+  t <- STArray.readArray c (500, 0)
+  return \$ isBlocked t
+
produce :: Cave s -> ST s Bool
-produce c = step (500, 0)
+produce c = do
+  full <- isFull c
+  if full then return False else step (500, 0)
where down (x,y) = f (x, succ y)
left (x,y) = f (pred x, succ y)
right (x,y) = f (succ x, succ y)

@@ 109,20 119,17 @@ produce c = step (500, 0)
STArray.writeArray c p Sand
return True

-partA :: Parse -> Int
-partA ls = runST \$ do
-  c <- initialCave ls
+part :: Bool -> Parse -> Int
+part fl ls = runST \$ do
+  c <- initialCave fl ls
loop 0 c
where loop n c = do
t <- produce c
if t then loop (succ n) c else return n

---partB :: Parse -> Parse
---partB = id
-
main :: IO ()
main = with parser \$ do
-  run' "14.example" "a example" partA 24
-  run' "14.input" "a input" partA 832
-  --run "14.example" "b example" partB
-  --run "14.input" "b input" partB
+  run' "14.example" "a example" (part False) 24
+  run' "14.input" "a input" (part False) 832
+  run' "14.example" "b example" (part True) 93
+  run' "14.input" "b input" (part True) 27601

```