Sattolo cycle: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Move to draft status, add related tasks)
Line 1: Line 1:
{{task|Classic CS problems and programs}}
{{draft task|Classic CS problems and programs}}


{{task heading}}
;Task:
Implement the   [[wp:Sattolo's algorithm|Sattolo cycle]]   for an integer array (or, if possible, an array of any type).
Implement the   [[wp:Sattolo's algorithm|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.
Sattolo cycle is use to shuffle an array ensuring each index is in a new position.

{{task heading|Related tasks}}

* [[Knuth Shuffle]]
<br><br>
<br><br>

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>
<lang csharp>

Revision as of 23:33, 29 August 2016

Sattolo cycle is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

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.

Related tasks



C#

<lang csharp> private static readonly Random Rand = new Random();

void sattoloCycle<T>(IList<T> items) {

   for (var i = items.Count; i-- > 1;) {
       int j = Rand.Next(i);
       var tmp = items[i];
       items[i] = items[j];
       items[j] = tmp;
   }

}</lang>

Java

<lang Java>private static final Random rng = new Random();

void sattoloCycle(Object[] items) {

   for (int i = items.length; i-- > 1;) {
       int j = rng.nextInt(i);
       Object tmp = items[i];
       items[i] = items[j];
       items[j] = tmp;
   }

}</lang>

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;
   }

}</lang>

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</lang>


TypeScript

<lang TypeScript>function sattoloCycle<T>(items: Array<T>): void {

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

}</lang>