Sattolo cycle: Difference between revisions
Content added Content deleted
(Create Sattolo cycle's page. It is use to shuffle an array ensuring each index is in a new position) |
(Add JavaScript) |
||
Line 7: | Line 7: | ||
<br><br> |
<br><br> |
||
=={{header| |
=={{header|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; |
|||
} |
|||
} |
|||
=={{header|Python}}== |
|||
<lang python>from random import randrange |
<lang python>from random import randrange |
||
Revision as of 20:30, 29 August 2016
Sattolo cycle
You are encouraged to solve this task according to the task description, using any language you may know.
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