Sattolo cycle: Difference between revisions

m
m (→‎{{header|Phix}}: added syntax colouring the hard way)
 
(40 intermediate revisions by 18 users not shown)
Line 54:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F sattolo_cycle(&items)
L(i) (items.len-1 .. 1).step(-1)
V j = random:(i)
Line 62:
V lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sattolo_cycle(&lst)
print(lst)</langsyntaxhighlight>
 
{{out}}
Line 69:
[3, 8, 9, 2, 1, 5, 4, 10, 7, 6]
[2, 9, 7, 5, 1, 3, 8, 10, 6, 4]
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintTable(INT ARRAY tab INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(32) FI
PrintI(tab(i))
OD
PrintE("]")
RETURN
 
PROC SattaloCycle(INT ARRAY tab INT size)
INT i,j,tmp
 
i=size-1
WHILE i>0
DO
j=Rand(i)
tmp=tab(i)
tab(i)=tab(j)
tab(j)=tmp
i==-1
OD
RETURN
 
PROC Test(INT ARRAY tab INT size)
Print("Original data: ")
PrintTable(tab,size)
SattaloCycle(tab,size)
Print("Shuffled data: ")
PrintTable(tab,size)
PutE()
RETURN
 
PROC Main()
INT ARRAY a=[10 20 30],b=[11 12 13 14 15 16 17 18 19 20 21 22]
 
Test(a,0)
Test(a,1)
Test(a,2)
Test(a,3)
Test(b,12)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sattolo_cycle.png Screenshot from Atari 8-bit computer]
<pre>
Original data: []
Shuffled data: []
 
Original data: [10]
Shuffled data: [10]
 
Original data: [10 20]
Shuffled data: [20 10]
 
Original data: [20 10 30]
Shuffled data: [10 30 20]
 
Original data: [11 12 13 14 15 16 17 18 19 20 21 22]
Shuffled data: [21 22 19 15 18 12 13 16 14 11 17 20]
</pre>
 
=={{header|ALGOL 68}}==
Arrays in Algol 68 need not have a lower bound of 0, other than that, this implements the pseudo code.
<langsyntaxhighlight lang="algol68">BEGIN
# reorders the elements of a using the Sattolo cycle #
# this operates on integer arrays, additional SATTOLO operators #
Line 97 ⟶ 161:
OD
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 111 ⟶ 175:
At its simplest, an AppleScript handler for the shuffle could be:
 
<langsyntaxhighlight lang="applescript">on sattoloShuffle(theList) -- In-place shuffle.
repeat with i from (count theList) to 2 by -1
set j to (random number from 1 to (i - 1))
Line 117 ⟶ 181:
end repeat
return -- Return nothing (ie. not the result of the last action above).
end sattoloShuffle</langsyntaxhighlight>
 
But swapping values by list is inefficient in a repeat. Also, if an AppleScript list is quite to very long, access to its items is very much faster if the list variable is referred to as a property belonging to something rather than simply as a variable. In addition to this, using the language's built-in <tt>some</tt> specifier to select an item at random from a list is so much faster than sending an Apple event to invoke the StandardAdditions' <tt>random number</tt> command that, for the current purpose, it can be over 100 times as fast to set up an index list of the same length and select indices at random from that!
 
<langsyntaxhighlight lang="applescript">on sattoloShuffle(theList) -- In-place shuffle.
-- Script object to which list variables can "belong".
script o
Line 157 ⟶ 221:
set output to output as text
set AppleScript's text item delimiters to astid
return output</langsyntaxhighlight>
 
{{output}}
Line 174 ⟶ 238:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 409 ⟶ 473:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">cycle: function [arr][
if 2 > size arr -> return arr
lastIndex: (size arr)-1
Line 436 ⟶ 500:
 
loop lists 'l ->
print [l "->" cycle l]</langsyntaxhighlight>
 
{{out}}
Line 445 ⟶ 509:
[10 20 30] -> [20 30 10]
[11 12 13 14 15 16 17 18 19 20 21 22] -> [14 11 18 17 12 20 16 19 21 22 15 13]</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">loop 3
{
testCases:= [[]
,[10]
,[10, 20]
,[10, 20, 30]
,[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]]
 
for n, items in testCases
{
Sattolo_cycle(items)
res := "["
for m, v in items
res .= v ", "
result .= Trim(res, ", ") "]`n"
}
result .= "`n"
}
MsgBox % result
return
 
Sattolo_cycle(ByRef items){
i := items.Count()
while (i>1)
{
Random, j, 1, i-1
t := items[i], items[i] := items[j], items[j] := t
i--
}
}
</syntaxhighlight>
{{out}}
<pre>[]
[10]
[20, 10]
[20, 30, 10]
[21, 15, 22, 17, 11, 12, 13, 14, 16, 18, 20, 19]
 
[]
[10]
[20, 10]
[20, 30, 10]
[18, 13, 20, 17, 19, 15, 21, 16, 14, 22, 12, 11]
 
[]
[10]
[20, 10]
[30, 10, 20]
[21, 17, 14, 12, 13, 11, 16, 22, 15, 18, 20, 19]</pre>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="bacon">OPTION BASE 1
 
SUB Swap_Array(array[], total)
Line 472 ⟶ 587:
 
DECLARE demo5[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 }
Swap_Array(demo5, UBOUND(demo5))</langsyntaxhighlight>
{{out}}
<pre>
Line 480 ⟶ 595:
20 30 10
16 19 15 21 14 22 11 20 13 17 18 12</pre>
 
=={{header|BQN}}==
Uses a fold in order to make the swaps in a functional style. It doesn't mutate the argument array, but after the initial copy is made CBQN is able to update it in place.
 
<syntaxhighlight lang="bqn">Sattolo ← {
Swap ← {
i 𝕊 𝕩:
j ← •rand.Range i
⌽⌾(i‿j⊸⊏) 𝕩
}
𝕩 Swap´ 1↓↕≠𝕩
}
 
>(⋈Sattolo)¨⟨
⟨⟩
⟨10⟩
⟨10, 20⟩
⟨10, 20, 30⟩
⟨11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22⟩
⟩</syntaxhighlight>
'''Possible Output:'''
<syntaxhighlight lang="bqn">┌─
╵ ⟨⟩
⟨ 10 ⟩
⟨ 20 10 ⟩
⟨ 20 30 10 ⟩
⟨ 17 20 15 22 19 21 16 14 18 13 12 11 ⟩
┘</syntaxhighlight>
 
=={{header|C}}==
This is generic to the extreme, although the function is technically being fed strings, it can handle any type, as shown in the outputs below :
===Interactive and without hardcoded inputs===
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<stdio.h>
Line 518 ⟶ 661:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 541 ⟶ 684:
===Non Interactive and with hardcoded inputs===
Same code but with hardcoded integer arrays as in the task to show that the function can handle any type.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<stdio.h>
Line 603 ⟶ 746:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 614 ⟶ 757:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">private static readonly Random Rand = new Random();
 
void sattoloCycle<T>(IList<T> items) {
Line 623 ⟶ 766:
items[j] = tmp;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <ctime>
#include <string>
Line 674 ⟶ 817:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 694 ⟶ 837:
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 722 ⟶ 865:
assert(a != b, "An element stayed in place unexpectedly.");
}
}</langsyntaxhighlight>
 
{{out}}
Line 731 ⟶ 874:
[5, 4, 3, 0, 2, 1]
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
procedure DoSattoloCycle(var IA: array of integer);
{Shuffle integers in array using Sattolo cycle}
var I,J,T: integer;
begin
{Make sure random number generator is random}
Randomize;
{Randomly shuffle every item in the array}
for I:=High(IA) downto 0 do
begin
J:=Random(I);
T:=IA[I]; IA[I]:=IA[J]; IA[J]:=T;
end;
end;
 
{Test data specified in problem}
 
var SatTest1: array of integer;
var SatTest2: array [0..0] of integer = (10);
var SatTest3: array [0..1] of integer = (10, 20);
var SatTest4: array [0..2] of integer = (10, 20, 30);
var SatTest5: array [0..11] of integer = (11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22);
 
 
procedure ShowSattoloCycle(Memo: TMemo);
 
procedure ShowIntArray(Title: string; IA: array of integer);
{Display title and array}
var I: integer;
var S: string;
begin
S:=Title+' [';
for I:=0 to High(IA) do
begin
if I<>0 then S:=S+' ';
S:=S+IntToStr(IA[I]);
end;
S:=S+']';
Memo.Lines.Add(S);
end;
 
 
procedure ShowShuffleData(var IA: array of integer);
{Shuffle and display specified array}
begin
ShowIntArray('Original data:', IA);
DoSattoloCycle(IA);
ShowIntArray('Shuffled data:',IA);
end;
 
 
begin
{Shuffle and display all data items}
ShowShuffleData(SatTest1);
ShowShuffleData(SatTest2);
ShowShuffleData(SatTest3);
ShowShuffleData(SatTest4);
ShowShuffleData(SatTest5);
end;
 
</syntaxhighlight>
{{out}}
<pre>
Original data: []
Shuffled data: []
Original data: [10]
Shuffled data: [10]
Original data: [10 20]
Shuffled data: [20 10]
Original data: [10 20 30]
Shuffled data: [20 30 10]
Original data: [11 12 13 14 15 16 17 18 19 20 21 22]
Shuffled data: [18 11 16 15 22 17 20 21 12 19 14 13]
Elapsed Time: 11.480 ms.
 
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
proc sattolo_cycle . a[] .
for i = len a[] downto 2
r = randint (i - 1)
swap a[r] a[i]
.
.
arr[] = [ 1 2 3 ]
sattolo_cycle arr[]
print arr[]
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let rnd=System.Random()
let sottolo(n:int[])=let rec fN g=match g with -1|0->() |_->let e=rnd.Next(g-1) in let l=n.[g] in n.[g]<-n.[e]; n.[e]<-l; fN (g-1) in fN((Array.length n)-1)
[[||];[|10|];[|10;20|];[|10;20;30|];[|11..22|]]|>List.iter(fun n->printf "%A->" n; sottolo n; printfn "%A" n)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 747 ⟶ 986:
</pre>
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays io kernel literals math math.ranges prettyprint
random sequences ;
IN: rosetta-code.sattolo-cycle
Line 768 ⟶ 1,007:
[ "original: " write . ]
[ "cycled: " write sattolo . ] bi nl
] each</langsyntaxhighlight>
{{out}}
<pre>
Line 788 ⟶ 1,027:
 
=={{header|Free Pascal}}==
<langsyntaxhighlight lang="pascal">program sattolocycle;
{$ifdef fpc}{$mode delphi}{$endif}
uses math;
var
a:Array of cardinal = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
i,j:integer;
t:cardinal;
begin
randomize;
a:=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
i := length(a);
while i > 01 do // do not touch this again!!!
begin
dec(i);
j :=randomrange(0,i); //Low() is always 0
t:=a[i];a[i]:=a[j];a[j]:=t;
write(a[i]:4);
end;
writeln;
end.</lang>
end.</syntaxhighlight>
<pre>
OutputExample output in Free Pascal:
2 14 12 13 0 1 15 9 7 6 3 18 10 4 16 5 19 8 11 17
Note output in Delphi differs because of different PRNG algorithms
</pre>
Note someone changed this and now it is incorrect.
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 22-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 860 ⟶ 1,097:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Starting array from 1 to 52
Line 867 ⟶ 1,104:
After Sattolo_Cycle
40 48 7 25 32 17 44 4 8 13 18 47 5 29 10 20 49 39 11 51 3 21 46 2 38 16 28 37 12 50 1 9 52 19 22 30 36 27 45 15 24 23 33 41 14 31 43 26 35 34 42 6</pre>
 
 
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
void local fn SattoloCycle( mutArr as CFMutableArrayRef )
NSUInteger i, j, count = len(mutArr)
for i = 0 to count - 1
cln j = arc4random_uniform( i );
MutableArrayExchangeObjects( mutArr, i, j )
next
end fn
 
NSUInteger i, count
CFMutableArrayRef mutArr
mutArr = fn MutableArrayWithArray( @[@"Alpha",@"Bravo",@"Charlie",@"Delta",@"Echo",@"Foxtrot"] )
 
for i = 0 to 5
fn SattoloCycle( mutArr )
NSLog( @"%@", mutArr )
next
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
(
Charlie,
Foxtrot,
Delta,
Bravo,
Alpha,
Echo
)
(
Echo,
Alpha,
Charlie,
Foxtrot,
Delta,
Bravo
)
(
Charlie,
Delta,
Foxtrot,
Bravo,
Echo,
Alpha
)
(
Delta,
Bravo,
Echo,
Alpha,
Charlie,
Foxtrot
)
(
Alpha,
Delta,
Foxtrot,
Echo,
Bravo,
Charlie
)
(
Echo,
Charlie,
Alpha,
Bravo,
Delta,
Foxtrot
)
</pre>
 
=={{header|Go}}==
<syntaxhighlight lang="go">
<lang go>
package main
 
Line 891 ⟶ 1,207:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 907 ⟶ 1,223:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad ((>=>), (>>=), forM_)
import Control.Monad.Primitive
import qualified Data.Vector as V
Line 943 ⟶ 1,259:
test [11..22 :: Int]
-- Also works for other types.
test "abcdef"</langsyntaxhighlight>
 
{{out}}
Line 968 ⟶ 1,284:
Implementation:
 
<langsyntaxhighlight Jlang="j">sattolo=:3 :0
for_i.}:i.-#y do.
j=.?i
Line 975 ⟶ 1,291:
y
)
</syntaxhighlight>
</lang>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> sattolo ''
 
sattolo ,10
Line 988 ⟶ 1,304:
30 10 20
sattolo 11+i.12
19 18 15 21 12 17 22 16 20 13 11 14</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight Javalang="java">private static final Random rng = new Random();
 
void sattoloCycle(Object[] items) {
Line 1,000 ⟶ 1,316:
items[j] = tmp;
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">function sattoloCycle(items) {
for (var i = items.length-1; i > 0; i--) {
var j = Math.floor(Math.random() * i);
Line 1,010 ⟶ 1,326:
items[j] = tmp;
}
}</langsyntaxhighlight>
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Sattolo cycle array shuffle, in Jsish */
function sattoloCycle(items:array):void {
for (var i = items.length-1; i > 0; i--) {
Line 1,045 ⟶ 1,361:
a ==> [ 22, 11, 17, 15, 12, 14, 19, 13, 21, 18, 16, 20 ]
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u sattoloCycle.jsi
[PASS] sattoloCycle.jsi</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
Neither the C nor the Go implementations of jq has a built-in PRNG, but both are designed with the Unix toolset philosophy in mind,
so in this entry we will use an external source of randomness rather than
one of the PRNGs defined in jq as at RC.
 
Specifically, we will use /dev/urandom like so:
 
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -RMnrc -f program.jq
 
where program.jq is the following program:
<syntaxhighlight lang="jq"># Output: a stream of prn in range(0;$n) where $n is . and $n > 1
def prns:
. as $n
| (($n-1)|tostring|length) as $w
# Output: a prn in range(0;$n)
| def prn:
[limit($w; inputs)] | join("") | tonumber
| if . < $n then . else prn end;
repeat(prn);
 
# Output: a prn in range(0;$n) where $n is .,
# b
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
def sattoloCycle:
length as $n
| if $n ==0 then []
elif $n == 1 then empty # a Sattolo cycle is not possible
else {i: $n, a: .}
| until(.i == 1; # n.b.
.i += -1
| (.i | prn) as $j # this line distinguishes the Sattolo cycle from the Knuth shuffle
| .a[.i] as $t
| .a[.i] = .a[$j]
| .a[$j] = $t)
| .a
end;
 
def task:
[],
[10,20],
[10,20,30],
[range(11;23)]
| sattoloCycle;
 
task</syntaxhighlight>
{{out}}
<pre>
[]
[20,10]
[20,30,10]
[17,13,14,15,20,21,19,16,18,22,12,11]
</pre>
 
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function sattolocycle!(arr::Array, last::Int=length(arr))
for i in last:-1:2
j = rand(1:i-1)
Line 1,065 ⟶ 1,445:
@show sattolocycle!([10])
@show sattolocycle!([10, 20, 30])
@show sattolocycle!([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22])</langsyntaxhighlight>
 
{{out}}
Line 1,074 ⟶ 1,454:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun <T> sattolo(items: Array<T>) {
Line 1,090 ⟶ 1,470:
sattolo(items)
println(items.joinToString())
}</langsyntaxhighlight>
Sample output:
{{out}}
Line 1,100 ⟶ 1,480:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function sattolo (items)
local j
for i = #items, 2, -1 do
Line 1,119 ⟶ 1,499:
sattolo(array)
print("[" .. table.concat(array, ", ") .. "]")
end</langsyntaxhighlight>
{{out}}
<pre>[]
Line 1,128 ⟶ 1,508:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE SattoloCycle;
FROM FormatString IMPORT FormatString;
FROM RandomNumbers IMPORT Randomize,Random;
Line 1,162 ⟶ 1,542:
 
ReadChar
END SattoloCycle.</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import random
 
proc sattoloCycle[T](a: var openArray[T]) =
var j = 0
if a.len < 2:
return
for i in countdown(a.high, 1):
let j = rand(int.high) mod i
swap a[j], a[i]
 
Line 1,197 ⟶ 1,574:
 
e.sattoloCycle()
echo "\nShuffled e = ", $e</langsyntaxhighlight>
 
{{out}}
Line 1,212 ⟶ 1,589:
=={{header|Objeck}}==
{{trans|Objeck}}
<langsyntaxhighlight lang="objeck">class Sattolo {
function : Main(args : String[]) ~ Nil {
array := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Line 1,228 ⟶ 1,605:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,236 ⟶ 1,613:
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface NSMutableArray (SattoloCycle)
Line 1,248 ⟶ 1,625:
}
}
@end</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sattolo_cycle arr =
for i = Array.length arr - 1 downto 1 do
let j = Random.int i in
Line 1,257 ⟶ 1,634:
arr.(i) <- arr.(j);
arr.(j) <- temp
done</langsyntaxhighlight>
 
=={{header|Pascal}}==
Pascal does not have a <tt>random</tt> function.
The following program complies with the ISO standard 7185 (Standard “Unextended” Pascal, level&nbsp;1) except the <tt>random</tt> function utilized has been supplied by the compiler vendor.
Although <tt>random</tt> is not standardized, the GPC (GNU Pascal Compiler), FPC (FreePascal compiler) and many other compilers support this UCSD Pascal extension.
<syntaxhighlight lang="pascal">program sattoloCycle(output);
 
var
i: integer;
sample1: array[0..0] of integer;
sample2: array[0..1] of integer;
sample3: array[0..2] of integer;
sample4: array[0..11] of integer;
 
procedure shuffle(var item: array[itemMinimum..itemMaximum: integer] of integer);
var
i, randomIndex, temporaryValue: integer;
begin
for i := itemMaximum downto succ(itemMinimum) do
begin
randomIndex := random(i - itemMinimum) + itemMinimum;
temporaryValue := item[randomIndex];
item[randomIndex] := item[i];
item[i] := temporaryValue
end
end;
 
procedure printArray(var item: array[itemMinimum..itemMaximum: integer] of integer);
var
i: integer;
begin
for i := itemMinimum to itemMaximum do
begin
write(item[i]:5)
end;
writeLn
end;
 
begin
sample1[0] := 10;
sample2[0] := 10; sample2[1] := 20;
sample3[0] := 10; sample3[1] := 20; sample3[2] := 30;
sample4[0] := 11; sample4[1] := 12; sample4[2] := 13; sample4[3] := 14;
sample4[4] := 15; sample4[5] := 16; sample4[6] := 17; sample4[7] := 18;
sample4[8] := 19; sample4[9] := 20; sample4[10] := 21; sample4[11] := 22;
shuffle(sample1); printArray(sample1);
shuffle(sample2); printArray(sample2);
shuffle(sample3); printArray(sample3);
shuffle(sample4); printArray(sample4);
end.</syntaxhighlight>
{{out}}
10
20 10
20 30 10
16 11 20 13 17 18 19 14 12 21 22 15
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">@a = 0..30;
 
printf "%2d ", $_ for @a; print "\n";
Line 1,272 ⟶ 1,705:
@$array[$j, $i] = @$array[$i, $j];
}
}</langsyntaxhighlight>
{{out}}
<pre> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Line 1,278 ⟶ 1,711:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">cards</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">52</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Before: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">cards</span>
Line 1,291 ⟶ 1,724:
<span style="color: #008080;">if</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cards</span><span style="color: #0000FF;">)!=</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">52</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Sorted: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cards</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre style="font-size: 12px">
Line 1,300 ⟶ 1,733:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">function sattoloCycle($items) {
for ($i = 0; $i < count($items); $i++) {
$j = floor((mt_rand() / mt_getrandmax()) * $i);
Line 1,309 ⟶ 1,742:
return $items;
}
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
Tests = [[],
[10],
[10, 20],
[10, 20, 30],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
"sattolo cycle"],
foreach(L in Tests)
println(original=L),
sattolo_cycle(L),
println(shuffled=L),
nl
end,
nl,
foreach(_ in 1..10)
L = 1..10,
sattolo_cycle(L),
println(L)
end.
 
sattolo_cycle(L) =>
foreach(I in L.len..-1..2)
swap(L,I,random(1,I-1))
end.
 
swap(L,I,J) =>
T = L[I],
L[I] := L[J],
L[J] := T.</syntaxhighlight>
 
{{out}}
<pre>original = []
shuffled = []
 
original = [10]
shuffled = [10]
 
original = [10,20]
shuffled = [20,10]
 
original = [10,20,30]
shuffled = [20,30,10]
 
original = [11,12,13,14,15,16,17,18,19,20,21,22]
shuffled = [17,15,11,16,20,12,21,19,22,18,14,13]
 
original = sattolo cycle
shuffled = a cyotltecsol
 
[7,6,10,1,3,5,8,2,4,9]
[6,10,5,8,7,3,9,1,2,4]
[9,4,10,5,8,1,3,7,2,6]
[7,10,4,2,6,1,8,3,5,9]
[3,1,9,5,7,2,10,4,8,6]
[8,10,2,5,6,9,3,4,7,1]
[7,10,2,5,9,4,3,6,1,8]
[8,7,1,10,6,4,3,9,5,2]
[9,1,2,6,3,7,8,5,10,4]
[7,4,8,10,9,2,5,1,6,3]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(seed (in "/dev/urandom" (rd 8)))
 
(de sattolo (Lst)
Line 1,322 ⟶ 1,816:
(println 'before L)
(sattolo L)
(println 'after L) )</langsyntaxhighlight>
{{out}}
<pre>
Line 1,332 ⟶ 1,826:
 
 
<langsyntaxhighlight lang="python">
>>> from random import randrange
>>> def sattoloCycle(items):
Line 1,357 ⟶ 1,851:
[2, 6, 5, 3, 9, 8, 10, 7, 1, 4]
[3, 6, 2, 5, 10, 4, 1, 9, 7, 8]
>>> </langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 1,363 ⟶ 1,857:
See [[Knuth shuffle#Quackery]] for notes re. the "in-place-ness" of this code.
 
<langsyntaxhighlight Quackerylang="quackery"> [ temp put
2dup swap
temp share swap peek
Line 1,378 ⟶ 1,872:
[ dup size 1 - times
[ i 1+ dup random
rot [exch] ] ] is sattolo ( [ --> [ )</langsyntaxhighlight>
 
{{Out}}
Line 1,418 ⟶ 1,912:
=={{header|R}}==
Basically identical to https://rosettacode.org/wiki/Knuth_shuffle#Short_version We've only changed an i to an i-1, changed the function names, and added the [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] test.
<langsyntaxhighlight rlang="rsplus">sattolo <- function(vec)
{
last <- length(vec)
if(last< >= 2){return(vec)}
else for(i in last:2)
{
j<-samplefor(1i in last:(i-1),12)
{
vec[c(i,j)]<-vec[c(j,i)]
j <- sample(seq_len(i - 1), size = 1)
vec[c(i, j)] <- vec[c(j, i)]
}
}
vec
Line 1,432 ⟶ 1,928:
sattolo(integer(0))
sattolo(c(10))
replicate(10, sattolo(c(10, 20)))
replicate(10, sattolo(c(10, 20, 30)))
sattolo(c(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22))
sattolo(c("Also", "works", "for", "strings"))</langsyntaxhighlight>
{{Out}}
<pre>> sattolo(integer(0))
Line 1,441 ⟶ 1,937:
> sattolo(c(10))
[1] 10
> replicate(10, sattolo(c(10, 20)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 20 20 20 20 20 20 20 20 20 20
[2,] 10 10 10 10 10 10 10 10 10 10
> replicate(10, sattolo(c(10, 20, 30)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 30 30 20 20 30 20 20 20 20 20
Line 1,452 ⟶ 1,948:
> sattolo(c(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22))
[1] 12 13 15 16 20 11 22 17 14 21 18 19
> sattolo(c("Also", "works", "for", "strings"))
[1] "strings" "for" "Also" "works" </pre>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
;; although the shuffle is in-place, returning the shuffled vector makes
Line 1,490 ⟶ 1,986:
v′
(check-true (derangement-of? #(11 12 13 14 15 16 17 18 19 20 21) v′)))</langsyntaxhighlight>
 
{{out}}
Line 1,500 ⟶ 1,996:
This modifies the array passed as argument, in-place.
 
<syntaxhighlight lang="raku" perl6line>sub sattolo-cycle (@array) {
for reverse 1 .. @array.end -> $i {
my $j = (^$i).pick;
Line 1,511 ⟶ 2,007:
say @a;
sattolo-cycle(@a);
say @a;</langsyntaxhighlight>
 
{{out|Sample output}}
Line 1,524 ⟶ 2,020:
 
The values of the array elements are specified via the command line (C.L.).
<langsyntaxhighlight lang="rexx">/*REXX program implements and displays a Sattolo shuffle for an array (of any type).*/
parse arg a; say 'original:' space(a) /*obtain args from the CL; display 'em.*/
do x=0 for words(a); @.x= word(a, x+1); end /*assign all elements to the @. array. */
Line 1,533 ⟶ 2,029:
$= /* [↓] build a list of shuffled items.*/
do k=0 for x; $= $ @.k; end /*k*/ /*append the next element in the array.*/
say ' Sattolo:' strip($) /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; [a null]}}
<pre>
Line 1,566 ⟶ 2,062:
 
=== version 2 ===
<langsyntaxhighlight lang="rexx">/* REXX */
n=25
Do i=0 To n
Line 1,589 ⟶ 2,085:
End
Say ol
Return</langsyntaxhighlight>
{{out}}
<pre> pre 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Line 1,595 ⟶ 2,091:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sattolo cycle
 
Line 1,619 ⟶ 2,115:
next
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z
i v 3 c 7 x 6 5 4 n a b r t e f g 2 8 u m o p w q l j h 9 s d y k z 1
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
DUP SIZE 2 '''FOR''' j
j 1 - RAND * FLOOR 1 +
DUP2 GET 3 PICK j GET SWAP 4 ROLLD PUT j ROT PUT
-1 '''STEP'''
≫ ‘'''SATLO'''’ STO
|
'''SATLO''' ''( { order } -- { reorder } )''
for j from last downto 2 do:
let k = random integer in range 0 ≤ k < j
swap items[j] with items[k]
|}
{{in}}
<pre>
[1 2 3 4 5 6] SATLO
</pre>
{{out}}
<pre>
1: [ 2 5 4 6 2 3 ]
</pre>
 
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">
> class Array
> def sattolo_cycle!
Line 1,654 ⟶ 2,180:
[9, 8, 4, 2, 6, 1, 5, 10, 3, 7]
[9, 4, 2, 7, 6, 1, 10, 3, 8, 5]
=> 10</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">a$ = "123456789abcdefghijklmnopqrstuvwxyz"
n = len(a$)
dim sit$(n) ' hold area to string
Line 1,684 ⟶ 2,210:
print
end sub
</langsyntaxhighlight><pre>Output:
1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z
d c 5 e v 3 n 7 8 h r p 2 y j l s x q 6 f 9 o a u i w 4 1 m g z t k b </pre>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">def shuffle[T](a: Array[T]): Array[T] = {
scala.util.Random.shuffle(a)
a
}</langsyntaxhighlight>
 
=={{header|SequenceL}}==
<syntaxhighlight lang="sequencel">
<lang sequenceL>
import <Utilities/Random.sl>;
import <Utilities/Sequence.sl>;
Line 1,711 ⟶ 2,237:
swapHelper(list(1), i(0), j(0), vali(0), valj(0)) := setElementAt(setElementAt(list, i, valj), j, vali);
 
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
Modifies the array in-place:
<langsyntaxhighlight lang="ruby">func sattolo_cycle(arr) {
for i in (arr.len ^.. 1) {
arr.swap(i, i.irand)
}
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight Smalltalklang="smalltalk">SequenceableCollection extend [
 
sattoloCycle
Line 1,730 ⟶ 2,256:
b := Random between: a+1 and: self size.
self swap: a with: b]]
]</langsyntaxhighlight>
Modifies the collection in-place. Collections that don't support that,
like strings, will throw an exception.
 
Use example:
<langsyntaxhighlight Smalltalklang="smalltalk">st> #() copy sattoloCycle
()
st> #(10) copy sattoloCycle
Line 1,748 ⟶ 2,274:
(22 13 17 18 14 12 15 21 16 11 20 19 )
st> 'Sattolo cycle' asArray sattoloCycle asString
'yocS talcelto'</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension Array {
public mutating func satalloShuffle() {
for i in stride(from: index(before: endIndex), through: 1, by: -1) {
Line 1,783 ⟶ 2,309:
 
print("\(testCase) shuffled = \(shuffled)")
}</langsyntaxhighlight>
 
{{out}}
Line 1,791 ⟶ 2,317:
[10, 20, 30] shuffled = [20, 30, 10]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] shuffled = [20, 22, 17, 12, 19, 14, 15, 13, 21, 16, 11, 18]</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd
 
MainModule: {
// Define an abstract type Vec to make the shuffling
// function polymorphic
Vec: typedef(Lambda<:Data Bool>(λ d :Data()
(starts-with (_META_type d) "Vector<"))),
 
sshuffle: (λ v Vec() locals: rnd 0
(for n in Range( (- (size v) 1) 0) do
(= rnd (randr (to-Int (- n 1))))
(with tmp (cp (get v n))
(set-el v n (get v rnd))
(set-el v rnd tmp))
)
(lout v)
),
_start: (λ
(with v [10,20,30,40,50,60,70,80,90,100]
(lout "Original:\n" v)
(lout "Shuffled:")
(sshuffle v))
(lout "")
(with v ["A","B","C","D","E","F","G","H"]
(lout "Original:\n" v)
(lout "Shuffled:")
(sshuffle (cp v)))
)
}</syntaxhighlight>
{{out}}
<pre>
Original:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Shuffled:
[20, 90, 100, 50, 30, 10, 60, 70, 40, 80]
 
Original:
["A", "B", "C", "D", "E", "F", "G", "H"]
Shuffled:
["E", "A", "H", "B", "G", "D", "C", "F"]
</pre>
 
=={{header|TypeScript}}==
<langsyntaxhighlight TypeScriptlang="typescript">function sattoloCycle<T>(items: Array<T>): void {
for (let i = items.length; i -= 1;) {
const j = Math.floor(Math.random() * i);
Line 1,800 ⟶ 2,369:
items[j] = tmp;
}
}</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Sub Sattolo(Optional ByRef a As Variant)
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
Line 1,852 ⟶ 2,421:
For Each i In f: Debug.Print i;: Next i: Debug.Print
End Sub
</langsyntaxhighlight>{{out}}<pre>Before:
After:
Before: 10
Line 1,867 ⟶ 2,436:
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
 
var rand = Random.new()
Line 1,888 ⟶ 2,457:
sattolo.call(test)
System.print("Sattolo : %(test)\n")
}</langsyntaxhighlight>
 
{{out}}
Sample run:
<pre>
Original: []
Line 1,912 ⟶ 2,482:
Original: [fgh, ijk, lmn, opq, rst, uvw, xyz]
Sattolo : [xyz, opq, rst, fgh, ijk, lmn, uvw]
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">proc Sattolo(Array, Items, BytesPerItem);
int Array, Items, BytesPerItem;
int I, J;
char Temp(8);
[for I:= Items-1 downto 1 do
[J:= Ran(I); \range [0..I-1]
CopyMem(Temp, Array+I*BytesPerItem, BytesPerItem);
CopyMem(Array+I*BytesPerItem, Array+J*BytesPerItem, BytesPerItem);
CopyMem(Array+J*BytesPerItem, Temp, BytesPerItem);
];
];
 
string 0; \use zero-terminated strings
int A; char B; real C;
int I;
[A:= [1, 2, 3, 4, 5];
Sattolo(A, 5, 4 \bytes per int\);
for I:= 0 to 5-1 do
[IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
B:= "12345";
Sattolo(B, 5, 1 \byte per char\);
for I:= 0 to 5-1 do
[ChOut(0, B(I)); ChOut(0, ^ )];
CrLf(0);
C:= [1., 2., 3., 4., 5.];
Sattolo(addr C(0), 5, 8 \bytes per real\);
for I:= 0 to 5-1 do
[RlOut(0, C(I)); ChOut(0, ^ )];
CrLf(0);
A:= [10];
Sattolo(A, 1, 4 \bytes per int\);
for I:= 0 to 1-1 do
[IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
]</syntaxhighlight>
 
{{out}}
<pre>
2 5 1 3 4
5 1 4 2 3
5.00000 4.00000 1.00000 3.00000 2.00000
10
</pre>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub sattolo$(l$)
local i, j, items$(1), n, t$
Line 1,938 ⟶ 2,554:
for n = 1 to 5
read item$ : print "[", sattolo$(item$), "]"
next</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn sattoloCycle(list){ // in place
foreach i in ([list.len()-1 .. 1,-1]){
list.swap(i,(0).random(i)); # 0 <= j < i
}
list
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">sattoloCycle([0..9].walk().copy()).println();
sattoloCycle("this is a test".split()).println();</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits