Give a sequence, the following algorithm generates the randomly shuffle the sequence elements.
open System
let rand = Random()
let shuffleYateFisher (data:seq<_>) =
let result = System.Collections.Generic.List<_> ()
data
|> Seq.iter (fun n ->
let index = rand.Next(0, result.Count)
if index = result.Count then
result.Add(n)
else
result.Add(result.[index])
result.[index] <- n)
result
let seq = seq { for i=0 to 10 do yield i }
for i=0 to 5 do
let l = shuffleYateFisher seq
l |> Seq.iter (printf "%A ")
printfn ""
No comments:
Post a Comment