Sattolo cycle

From Rosetta Code
Revision as of 20:30, 29 August 2016 by rosettacode>Aloisdg (Add JavaScript)
Task
Sattolo cycle
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Implement the   Sattolo cycle   for an integer array (or, if possible, an array of any type).

Sattolo cycle is use to shuffle an array ensuring each index is in a new position.

JavaScript

<lang JavaScript>function sattoloCycle(items) {

   for (var i = items.length; i--> 1;) {
       var j = Math.floor(Math.random() * i);
       var tmp = items[i];
       items[i] = items[j];
       items[j] = tmp;
   }

}

Python

<lang python>from random import randrange

def sattoloCycle(items):

   i = len(items)
   while i > 1:
       i = i - 1
       j = randrange(i)  # 0 <= j <= i-1
       items[j], items[i] = items[i], items[j]
   return