summary refs log tree commit diff stats
path: root/solutions
diff options
context:
space:
mode:
authorBrian Chu <brianmchu42@gmail.com>2022-12-28 22:58:47 -0800
committerBrian Chu <brianmchu42@gmail.com>2022-12-28 22:58:47 -0800
commite550d5e41938086d4c893f9ebadfe6a62ba08c8f (patch)
treec5518084a0d35f399b4ee57ee6bd8963e6459e18 /solutions
parent9550a21d6136c3d9ba509520842678fa6cd1e57d (diff)
downloadAdventOfCode2022-e550d5e41938086d4c893f9ebadfe6a62ba08c8f.tar.gz
solution for day 14
Diffstat (limited to 'solutions')
-rw-r--r--solutions/day14.fs46
1 files changed, 46 insertions, 0 deletions
diff --git a/solutions/day14.fs b/solutions/day14.fs
new file mode 100644
index 0000000..0bc0464
--- /dev/null
+++ b/solutions/day14.fs
@@ -0,0 +1,46 @@
+module Solutions.Day14
+
+open System
+open System.IO
+
+let lineToCoords (line: string) =
+    line.Split([|","; " -> "|], StringSplitOptions.None) 
+    |> Array.map int
+    |> Array.chunkBySize 2
+    |> Array.map (fun x -> x[0], x[1])
+
+let coordsToPointSet (coords: (int * int) array) =
+    let coordLine (x1, y1) (x2, y2) =
+        seq { for x in min x1 x2 .. max x1 x2 do for y in min y1 y2 .. max y1 y2 -> (x, y) }
+        |> Set.ofSeq
+    Array.fold2 (fun points coord1 coord2 -> coordLine coord1 coord2 |> Set.union points) Set.empty coords[..Array.length coords - 2] coords[1..]
+
+let cave = File.ReadAllLines("inputs/day14.txt") |> Array.map (lineToCoords >> coordsToPointSet) |> Set.unionMany
+
+let startPoint = (500, 0)
+
+let rec watch abyss (cave, p1) =
+    let rec drop cave p1 (x, y) =
+        [ x, y+1; x-1, y+1; x+1, y+1]
+        |> Seq.tryFind (fun n -> not (Set.contains n cave))
+        |> (function
+            | None -> Set.add (x, y) cave, p1
+            | Some (nx, ny) when ny = abyss ->
+                Set.add (nx, ny) cave,
+                (if p1 = -1 then Set.count cave else p1)
+            | Some n -> drop cave p1 n)
+    
+    if Set.contains startPoint cave then 
+        (p1, Set.count cave)
+    else
+        watch abyss (drop cave p1 startPoint)
+
+let solution =
+    let abyss = (cave |> Seq.maxBy snd |> snd) + 1
+    let r = Set.count cave
+    let rns = watch abyss (cave, -1)
+    (fst rns - r), (snd rns - r)
+
+let part1 () = fst solution
+
+let part2 () = snd solution
\ No newline at end of file