Skip to content

Instantly share code, notes, and snippets.

@object
Created December 9, 2020 05:57
Show Gist options
  • Select an option

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

Select an option

Save object/34d1bd1697742d1a972e0850a586deb0 to your computer and use it in GitHub Desktop.
AdventOfCode 2020, December 9
let input =
File.ReadAllLines("Data/input09.txt")
|> Seq.toArray
|> Array.map Int64.Parse
// Reused from Day 1
let rec findNwithSum sum n numbers acc_sum acc_numbers =
if sum < 0L || n < 0 then
None
else if sum = 0L && n = 0 then
Some acc_numbers
else
match numbers with
| [] -> None
| head :: tail ->
match findNwithSum (sum-head) (n-1) tail (acc_sum+head) (head::acc_numbers) with
| Some result -> Some result
| None -> findNwithSum sum n tail acc_sum acc_numbers
let rec findFirstNotValid size =
input
|> Array.mapi (fun i x ->
if i < size then
x, [x]
else
match findNwithSum x 2 (List.ofArray input.[i-size..i-1]) 0L [] with
| Some s -> x, s
| None -> x, [])
|> Array.filter (fun (i,v) -> List.isEmpty v)
|> Array.head
|> fst
let notValid = findFirstNotValid 25
let rec findContiguousSet sum setSize ndx =
if ndx + setSize >= input.Length then
Array.empty
else
let slice = input.[ndx..ndx+setSize-1]
if slice |> Array.sum = sum then slice
else findContiguousSet sum setSize (ndx+1)
for setSize in [2..input.Length-1] do
let result = findContiguousSet notValid setSize 0
if result.Length > 0 then
printfn "%A" <| (result |> Array.min) + (result |> Array.max)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment