Skip to content

Instantly share code, notes, and snippets.

@object
Created December 14, 2023 18:50
Show Gist options
  • Select an option

  • Save object/4c34c983433c699516d44c665ac20d8d to your computer and use it in GitHub Desktop.

Select an option

Save object/4c34c983433c699516d44c665ac20d8d to your computer and use it in GitHub Desktop.
Advent of Code 2023, December 14
open System
open System.IO
let input =
File.ReadAllLines(__SOURCE_DIRECTORY__ + "/../data/input14.txt")
|> Seq.toArray
|> Array.map Seq.toArray
let swapRowsAndCols (pattern : char array array) =
let swapped = Array.zeroCreate<char array> pattern[0].Length
for i in [0..pattern[0].Length-1] do swapped.[i] <- Array.zeroCreate pattern.Length
for i in [0..pattern[0].Length-1] do
for j in [0..pattern.Length-1] do
swapped[i][j] <- pattern[j][i]
swapped
let rec tiltRow row =
match row |> Array.tryFindIndex (fun x -> x = '#') with
| Some cubeIndex -> Array.concat [|tiltRow (row[0..cubeIndex-1]); [|'#'|]; tiltRow (row[cubeIndex+1..row.Length-1]) |]
| None ->
let roundCount = row |> Array.filter (fun x -> x = 'O') |> Array.length
Array.concat [|Array.create roundCount 'O'; Array.create (row.Length - roundCount) '.'|]
let tiltNorth input =
input |> swapRowsAndCols |> Array.map tiltRow |> swapRowsAndCols
let tiltWest input =
input |> Array.map tiltRow
let tiltSouth input =
input |> Array.rev |> swapRowsAndCols |> Array.map tiltRow |> swapRowsAndCols |> Array.rev
let tiltEast input =
input |> Array.map Array.rev |> Array.map tiltRow |> Array.map Array.rev
let computeLoad input =
input
|> Array.map (fun row -> row |> Array.filter (fun c -> c = 'O') |> Array.length)
|> Array.mapi (fun ndx count -> (input.Length-ndx) * count)
|> Array.sum
// Part One
input
|> tiltNorth
|> computeLoad
// Part Two
let tiltCycle input =
input
|> tiltNorth
|> tiltWest
|> tiltSouth
|> tiltEast
let numCycles = 1000000000
let rec findLoop input acc =
let next = input |> tiltCycle
match acc |> List.rev |> List.tryFindIndex (fun x -> x = next) with
| Some index -> acc |> List.rev |> List.skip index, index
| None ->
findLoop next (next:: acc)
let loop, startIndex = findLoop input []
loop[(numCycles-startIndex-1) % loop.Length]
|> computeLoad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment