Skip to content

Instantly share code, notes, and snippets.

@object
Created December 9, 2023 06:38
Show Gist options
  • Select an option

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

Select an option

Save object/e1f009957be303cce2a4d5cd5b56a8f4 to your computer and use it in GitHub Desktop.
Advent of Code 2023, December 9
#time "on"
open System
open System.IO
let input =
File.ReadAllLines(__SOURCE_DIRECTORY__ + "/../data/input09.txt")
|> Seq.map (fun line -> line.Split " " |> Seq.map Int64.Parse |> Seq.toList)
|> Seq.toList
let nextSequence (values: int64 list) =
values |> List.pairwise
|> List.map (fun (x,y) -> y - x)
// Part One
let rec transform1 rowHistory =
if rowHistory |> List.last |> List.forall (fun x -> x = 0L) then
rowHistory |> List.fold (fun acc elt -> acc + (elt |> List.last)) 0L
else
let nextRow = rowHistory |> List.last |> nextSequence
nextRow :: (rowHistory |> List.rev) |> List.rev |> transform1
input
|> List.map (fun row -> transform1 [row])
|> List.sum
// Part Two
let rec transform2 acc (data: int64 list) =
match data, acc with
| [], _ -> acc
| head :: tail, [] -> transform2 [head] tail
| head :: tail, accHead :: accTail -> transform2 ((head - accHead) :: accHead :: accTail) tail
let rec extrapolateHistory rowHistory =
if rowHistory |> List.last |> List.forall (fun x -> x = 0L) then
rowHistory |> List.map List.head |> List.rev |> transform2 []
else
let nextRow = rowHistory |> List.last |> nextSequence
nextRow :: (rowHistory |> List.rev) |> List.rev |> extrapolateHistory
input
|> List.map (fun row -> extrapolateHistory [row])
|> List.map List.head
|> List.sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment