Created
December 9, 2023 06:38
-
-
Save object/e1f009957be303cce2a4d5cd5b56a8f4 to your computer and use it in GitHub Desktop.
Advent of Code 2023, December 9
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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