0 people like it.

Sequence Random Permutation

A generic function that randomly permutes the elements of a sequence.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
open System
 
let rec scramble (sqn : seq<'T>) = 
    let rnd = new Random()
    /// Removes an element from a sequence.
    let remove n sqn = sqn |> Seq.filter (fun x -> x <> n)
 
    seq {
        let x = sqn |> Seq.nth (rnd.Next(0, (sqn |> Seq.length)  - 1))
        yield x
        let sqn' = remove x sqn
        if not (sqn' |> Seq.isEmpty) then
            yield! scramble sqn'
    }
 
// Example:
let test = scramble ['1' .. '9'] |> Seq.toList
// Output:
// val test : char list = ['3'; '6'; '7'; '5'; '4'; '8'; '2'; '1'; '9']
namespace System
val scramble : sqn:seq<'T> -> seq<'T> (requires equality)

Full name: Script.scramble
val sqn : seq<'T> (requires equality)
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val rnd : Random
Multiple items
type Random =
  new : unit -> Random + 1 overload
  member Next : unit -> int + 2 overloads
  member NextBytes : buffer:byte[] -> unit
  member NextDouble : unit -> float

Full name: System.Random

--------------------
Random() : unit
Random(Seed: int) : unit
val remove : ('a -> seq<'a> -> seq<'a>) (requires equality)


 Removes an element from a sequence.
val n : 'a (requires equality)
val sqn : seq<'a> (requires equality)
module Seq

from Microsoft.FSharp.Collections
val filter : predicate:('T -> bool) -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.filter
val x : 'a (requires equality)
val x : 'T (requires equality)
val nth : index:int -> source:seq<'T> -> 'T

Full name: Microsoft.FSharp.Collections.Seq.nth
Random.Next() : int
Random.Next(maxValue: int) : int
Random.Next(minValue: int, maxValue: int) : int
val length : source:seq<'T> -> int

Full name: Microsoft.FSharp.Collections.Seq.length
val sqn' : seq<'T> (requires equality)
val not : value:bool -> bool

Full name: Microsoft.FSharp.Core.Operators.not
val isEmpty : source:seq<'T> -> bool

Full name: Microsoft.FSharp.Collections.Seq.isEmpty
val test : char list

Full name: Script.test
val toList : source:seq<'T> -> 'T list

Full name: Microsoft.FSharp.Collections.Seq.toList
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/16
Posted:7 years ago
Author:Taha Hachana
Tags: seq , sequence , random , permutation