Random permutation

By Aion- on Sep 11, 2012

Performs a uniform random permutation on the given elements.

Examples:
//var %x = 0 | while (%x < 3) { echo -a $randomPermutation(a,b,v,d,t) | inc %x }
b t a v d
d t b v a
d a b t v

/*
Performs a uniform random permutation to the given parameters.
*/
alias randomPermutation {
  var %length $0
  if (%length < 1) {
    return $iif($v1 < 0, $null, $1)
  }
  var %elements $1-
  var %index 1
  while (%index < %length) {
    var %newIndex $rand(%index, %length)
    if (%index == %newIndex) {
      continue
    }
    var %token $gettok(%elements, %index, 32)
    var %newToken $gettok(%elements, %newIndex, 32)

    ; todo implement a $swaptok function
    %elements = $remtok(%elements, %token, 1, 32)
    %elements = $remtok(%elements, %newToken, 1, 32)

    %elements = $instok(%elements, %newToken, %index, 32)
    %elements = $instok(%elements, %token, %newIndex, 32)

    inc %index
  }
  return %elements
}

Comments

Sign in to comment.
cptpan   -  Sep 22, 2012

Disregard

 Respond  
Aion-   -  Sep 22, 2012

What can't you understand about this snippet?

 Respond  
cptpan   -  Sep 22, 2012

wat

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.