Skip to content

Instantly share code, notes, and snippets.

@object
Created December 11, 2023 16:45
Show Gist options
  • Save object/59becfdbb7f090b512e237bad71fb296 to your computer and use it in GitHub Desktop.
Save object/59becfdbb7f090b512e237bad71fb296 to your computer and use it in GitHub Desktop.
Advent of Code 2023, December 11
#time "on"
open System.IO
let input =
File.ReadAllLines(__SOURCE_DIRECTORY__ + "/../data/input11.txt")
|> Seq.toArray
|> Array.map Seq.toArray
let grid =
input
|> Array.mapi (fun i col -> col |> Array.mapi (fun j c -> (int64 i, int64 j), c))
|> Array.concat
let getEmptyCols grid extraCount =
[0L..int64 input[0].Length-1L]
|> List.filter (fun x -> grid |> Array.filter (fun (pos, _) -> x = snd pos) |> Array.forall (fun (_, c) -> c = '.'))
|> List.mapi (fun ndx num -> num + int64 ndx * extraCount)
let getEmptyRows grid extraCount =
[0L..int64 input.Length-1L]
|> List.filter (fun x -> grid |> Array.filter (fun (pos, _) -> x = fst pos) |> Array.forall (fun (_, c) -> c = '.'))
|> List.mapi (fun ndx num -> num + int64 ndx * extraCount)
let rec expandGridCols colNums extraCount acc =
match colNums with
| [] -> acc
| colNum :: colNums ->
let newAcc =
acc
|> Array.map (fun ((x: int64,y: int64), c) -> if y <= colNum then ((x,y),c) else ((x,y+extraCount),c))
|> Array.sortBy fst
expandGridCols colNums extraCount newAcc
let rec expandGridRows rowNums extraCount acc =
match rowNums with
| [] -> acc
| rowNum :: rowNums ->
let newAcc =
acc
|> Array.map (fun ((x: int64,y: int64), c) -> if x <= rowNum then ((x,y),c) else ((x+extraCount,y),c))
|> Array.sortBy fst
expandGridRows rowNums extraCount newAcc
let findGalaxies grid =
grid |> Array.filter (fun elt -> snd elt = '#') |> Array.map fst
let getPairs grid =
seq {
for x in grid do
for y in grid do
if y > x then yield (x, y)
}
|> Seq.toArray
let getShortestPath pos1 pos2 =
let x1,y1 = pos1
let x2,y2 = pos2
let xdiff = if x1 > x2 then x1-x2 else x2-x1
let ydiff = if y1 > y2 then y1-y2 else y2-y1
xdiff + ydiff
let solve grid extraCount =
let emptyCols = getEmptyCols grid extraCount
let emptyRows = getEmptyRows grid extraCount
grid
|> expandGridCols emptyCols extraCount
|> expandGridRows emptyRows extraCount
|> findGalaxies
|> getPairs
|> Array.map (fun (x,y) -> getShortestPath x y)
|> Array.sum
// Part One
solve grid 1L
// Part Two
solve grid 999999L
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment