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: 
20: 
21: 
open System
 
let scramble (sqn : seq<'T>) = 
    let rnd = new Random()
    let rec scramble2 (sqn : seq<'T>) = 
        /// 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))
            yield x
            let sqn' = remove x sqn
            if not (sqn' |> Seq.isEmpty) then
                yield! scramble2 sqn'
        }
    scramble2 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 scramble2 : (seq<'T> -> seq<'T>) (requires equality)
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)
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

More information

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