Skip to content

Instantly share code, notes, and snippets.

@SteveGilham
Created September 29, 2020 18:32
Show Gist options
  • Save SteveGilham/ac08e38e314728f2c71167cef7e39d3c to your computer and use it in GitHub Desktop.
Save SteveGilham/ac08e38e314728f2c71167cef7e39d3c to your computer and use it in GitHub Desktop.
Faster version
open System
open System.Collections.Generic
open System.IO
let words = File.ReadAllLines(@".\brit-a-z.txt")
|> Array.filter (fun x -> x.IndexOf('\'') < 0)
let nines = words
|> Array.filter (fun x -> x.StartsWith("a"))
|> Array.filter (fun x -> x.Length = 9)
printfn "%d candidate words" nines.Length
let fives = words
|> Array.filter (fun x -> x.Length = 5)
printfn "%d candidate sub-words" fives.Length
let bag (x : String) = x |> Seq.cast<Char>
let takeChar (c : Char) (l : List<Char>) =
if l.Remove(c) then Some l
else None
let takeChars (l : Char seq) (c : Char seq) =
Seq.fold (fun l' c' -> Option.bind (takeChar c') l') (Some (List<Char>(l))) c
let solutions (t9 : Char seq) =
let l5 = fives
|> Array.map (fun x -> (x, bag x))
|> Array.filter (fun x -> Option.isSome (takeChars t9 (snd x)))
let matches = l5
|> Seq.map (fun x -> l5
|> Array.filter (fun y -> ((fst x).Chars 2) = ((fst y).Chars 0))
|> Array.filter (fun y -> let all = Seq.skip 1 (Seq.concat [| snd y ; snd x |])
Option.isSome (takeChars t9 all))
|> Array.map (fun y -> (fst x, fst y)))
|> Seq.concat
matches |> Seq.toList
let suitable (t9 : string) =
match solutions (bag t9) with
| x :: [] -> Some (t9, x)
| _ -> None
printfn "%A" (suitable "supernova")
let sw1 = System.Diagnostics.Stopwatch.StartNew()
let total = nines
|> Seq.choose suitable
|> Seq.map (fun x -> printfn "%A" x
x)
|> Seq.length
printfn "%A" total
sw1.Stop()
printfn "%A" (sw1.Elapsed)
;;
//9
//00:00:03.0791484
//161
//00:00:38.0018055
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment