Created
January 21, 2023 23:33
-
-
Save HarryMcCarney/6792955d5755fb16c96835c4a72edb6a to your computer and use it in GitHub Desktop.
This file contains 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
open System.Collections.Generic | |
let mutable terms = new Dictionary<int64, int>() | |
let isPower2 (x: int64) = | |
x &&& (x - 1L) = 0 | |
let addSeqToDict (t: int64 array) = | |
t | |
|> Array.rev | |
|> Array.mapi(fun i x -> terms.TryAdd(x,(i+1) )) | |
|> ignore | |
let addSeqToDictWithOffset (t: int64 array) (o:int) = | |
t | |
|> Array.rev | |
|> Array.filter(fun x -> x > 1) | |
|> Array.mapi(fun i x -> terms.TryAdd(x, (i+1+o)) ) | |
|> ignore | |
let evenFunc x = | |
x / 2L | |
let oddFunc x = | |
(x * 3L) + 1L | |
let rec genCollatz (sequence: int64 array) = | |
let n = sequence |> Array.last | |
if n = 1 then printfn "%A" sequence; addSeqToDict sequence | |
else | |
let f = if n % 2L = 0 then evenFunc else oddFunc | |
match terms.TryGetValue (f n) with | |
| (true, _) as (b, v) -> addSeqToDictWithOffset sequence v | |
| (false, _) as (b, v) -> genCollatz (Array.append sequence [|f n|]) | |
//populate mutable dictionary | |
[|1L..999999L|] | |
|> Array.rev | |
|> Array.filter (fun x -> not (isPower2 x)) | |
|> Array.map(fun x -> genCollatz [|x|] ) | |
//get key(n) of highest value(no of terms) in dictionary | |
terms :> seq<_> | |
|> Seq.map (|KeyValue|) | |
|> Seq.filter(fun (k,v) -> v = (terms.Values | |
|> Seq.max)) //ugly | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment