Sattolo cycle: Difference between revisions
Content added Content deleted
(Add Java) |
(Add Csharp) |
||
Line 6: | Line 6: | ||
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. |
||
<br><br> |
<br><br> |
||
=={{header|C sharp|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> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
<lang Java>void sattoloCycle(Object[] items) { |
<lang Java>void sattoloCycle(Object[] items) { |
Revision as of 20:50, 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.
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>void sattoloCycle(Object[] items) {
for (int i = items.length; i-- > 1;) { int j = (int) (Math.random() * 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>