Sattolo cycle: Difference between revisions
m
→{{header|EasyLang}}
Alpha bravo (talk | contribs) |
|||
(32 intermediate revisions by 15 users not shown) | |||
Line 54:
{{trans|Python}}
<
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)</
{{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.
<
# reorders the elements of a using the Sattolo cycle #
# this operates on integer arrays, additional SATTOLO operators #
Line 97 ⟶ 161:
OD
END
</syntaxhighlight>
{{out}}
<pre>
Line 111 ⟶ 175:
At its simplest, an AppleScript handler for the shuffle could be:
<
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</
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!
<
-- 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</
{{output}}
Line 174 ⟶ 238:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 409 ⟶ 473:
</syntaxhighlight>
=={{header|Arturo}}==
<
if 2 > size arr -> return arr
lastIndex: (size arr)-1
Line 436 ⟶ 500:
loop lists 'l ->
print [l "->" cycle l]</
{{out}}
Line 447 ⟶ 511:
=={{header|AutoHotkey}}==
<
{
testCases:= [[]
Line 477 ⟶ 541:
}
}
</syntaxhighlight>
{{out}}
<pre>[]
Line 498 ⟶ 562:
=={{header|BaCon}}==
<
SUB Swap_Array(array[], total)
Line 523 ⟶ 587:
DECLARE demo5[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 }
Swap_Array(demo5, UBOUND(demo5))</
{{out}}
<pre>
Line 531 ⟶ 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">
#include<stdlib.h>
#include<stdio.h>
Line 569 ⟶ 661:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 592 ⟶ 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">
#include<stdlib.h>
#include<stdio.h>
Line 654 ⟶ 746:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 665 ⟶ 757:
=={{header|C sharp|C#}}==
<
void sattoloCycle<T>(IList<T> items) {
Line 674 ⟶ 766:
items[j] = tmp;
}
}</
=={{header|C++}}==
<
#include <ctime>
#include <string>
Line 725 ⟶ 817:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 745 ⟶ 837:
=={{header|D}}==
<
void main() {
Line 773 ⟶ 865:
assert(a != b, "An element stayed in place unexpectedly.");
}
}</
{{out}}
Line 781 ⟶ 873:
[3, 5, 4, 1, 0, 2]
[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
swap a[r] a[i]
.
.
arr[] = [ 1 2 3 ]
print arr[]
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
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>
{{out}}
<pre>
Line 809 ⟶ 986:
</pre>
=={{header|Factor}}==
<
random sequences ;
IN: rosetta-code.sattolo-cycle
Line 830 ⟶ 1,007:
[ "original: " write . ]
[ "cycled: " write sattolo . ] bi nl
] each</
{{out}}
<pre>
Line 850 ⟶ 1,027:
=={{header|Free Pascal}}==
<
{$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;
i := length(a);
while i >
begin
dec(i);
j :=randomrange(0,i);
t:=a[i];a[i]:=a[j];a[j]:=t;
write(a[i]:4);
end;
writeln;
end.</syntaxhighlight>
<pre>
2 14 12 13 0 1 15 9 7 6 3 18 10 4 16 5 19 8 11 17
</pre>
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 922 ⟶ 1,097:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>Starting array from 1 to 52
Line 929 ⟶ 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">
package main
Line 953 ⟶ 1,207:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 969 ⟶ 1,223:
=={{header|Haskell}}==
<
import Control.Monad.Primitive
import qualified Data.Vector as V
Line 1,005 ⟶ 1,259:
test [11..22 :: Int]
-- Also works for other types.
test "abcdef"</
{{out}}
Line 1,030 ⟶ 1,284:
Implementation:
<
for_i.}:i.-#y do.
j=.?i
Line 1,037 ⟶ 1,291:
y
)
</syntaxhighlight>
Example use:
<
sattolo ,10
Line 1,050 ⟶ 1,304:
30 10 20
sattolo 11+i.12
19 18 15 21 12 17 22 16 20 13 11 14</
=={{header|Java}}==
<
void sattoloCycle(Object[] items) {
Line 1,062 ⟶ 1,316:
items[j] = tmp;
}
}</
=={{header|JavaScript}}==
<
for (var i = items.length-1; i > 0; i--) {
var j = Math.floor(Math.random() * i);
Line 1,072 ⟶ 1,326:
items[j] = tmp;
}
}</
=={{header|Jsish}}==
<
function sattoloCycle(items:array):void {
for (var i = items.length-1; i > 0; i--) {
Line 1,107 ⟶ 1,361:
a ==> [ 22, 11, 17, 15, 12, 14, 19, 13, 21, 18, 16, 20 ]
=!EXPECTEND!=
*/</
{{out}}
Line 1,126 ⟶ 1,380:
where program.jq is the following program:
<
def prns:
. as $n
Line 1,167 ⟶ 1,421:
| sattoloCycle;
task</
{{out}}
<pre>
Line 1,180 ⟶ 1,434:
{{works with|Julia|0.6}}
<
for i in last:-1:2
j = rand(1:i-1)
Line 1,191 ⟶ 1,445:
@show sattolocycle!([10])
@show sattolocycle!([10, 20, 30])
@show sattolocycle!([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22])</
{{out}}
Line 1,200 ⟶ 1,454:
=={{header|Kotlin}}==
<
fun <T> sattolo(items: Array<T>) {
Line 1,216 ⟶ 1,470:
sattolo(items)
println(items.joinToString())
}</
Sample output:
{{out}}
Line 1,226 ⟶ 1,480:
=={{header|Lua}}==
<
local j
for i = #items, 2, -1 do
Line 1,245 ⟶ 1,499:
sattolo(array)
print("[" .. table.concat(array, ", ") .. "]")
end</
{{out}}
<pre>[]
Line 1,254 ⟶ 1,508:
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM RandomNumbers IMPORT Randomize,Random;
Line 1,288 ⟶ 1,542:
ReadChar
END SattoloCycle.</
=={{header|Nim}}==
{{trans|C}}
<
proc sattoloCycle[T](a: var openArray[T]) =
Line 1,320 ⟶ 1,574:
e.sattoloCycle()
echo "\nShuffled e = ", $e</
{{out}}
Line 1,335 ⟶ 1,589:
=={{header|Objeck}}==
{{trans|Objeck}}
<
function : Main(args : String[]) ~ Nil {
array := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Line 1,351 ⟶ 1,605:
}
}
</syntaxhighlight>
Output:
Line 1,359 ⟶ 1,613:
=={{header|Objective-C}}==
<
@interface NSMutableArray (SattoloCycle)
Line 1,371 ⟶ 1,625:
}
}
@end</
=={{header|OCaml}}==
<
for i = Array.length arr - 1 downto 1 do
let j = Random.int i in
Line 1,380 ⟶ 1,634:
arr.(i) <- arr.(j);
arr.(j) <- temp
done</
=={{header|Pascal}}==
Pascal does not have a <tt>random</tt> function.
The following program complies with the ISO standard 7185 (Standard “Unextended” Pascal, level 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}}==
<
printf "%2d ", $_ for @a; print "\n";
Line 1,395 ⟶ 1,705:
@$array[$j, $i] = @$array[$i, $j];
}
}</
{{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,401 ⟶ 1,711:
=={{header|Phix}}==
<!--<
<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,414 ⟶ 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>
<!--</
{{out}}
<pre style="font-size: 12px">
Line 1,423 ⟶ 1,733:
=={{header|PHP}}==
<
for ($i = 0; $i < count($items); $i++) {
$j = floor((mt_rand() / mt_getrandmax()) * $i);
Line 1,432 ⟶ 1,742:
return $items;
}
</syntaxhighlight>
=={{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}}==
<
(de sattolo (Lst)
Line 1,445 ⟶ 1,816:
(println 'before L)
(sattolo L)
(println 'after L) )</
{{out}}
<pre>
Line 1,455 ⟶ 1,826:
<
>>> from random import randrange
>>> def sattoloCycle(items):
Line 1,480 ⟶ 1,851:
[2, 6, 5, 3, 9, 8, 10, 7, 1, 4]
[3, 6, 2, 5, 10, 4, 1, 9, 7, 8]
>>> </
=={{header|Quackery}}==
Line 1,486 ⟶ 1,857:
See [[Knuth shuffle#Quackery]] for notes re. the "in-place-ness" of this code.
<
2dup swap
temp share swap peek
Line 1,501 ⟶ 1,872:
[ dup size 1 - times
[ i 1+ dup random
rot [exch] ] ] is sattolo ( [ --> [ )</
{{Out}}
Line 1,541 ⟶ 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.
<
{
last <- length(vec)
if(last
{
{
j <- sample(seq_len(i - 1), size = 1)
vec[c(i, j)] <- vec[c(j, i)]
}
}
vec
Line 1,555 ⟶ 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"))</
{{Out}}
<pre>> sattolo(integer(0))
Line 1,564 ⟶ 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,575 ⟶ 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}}==
<
;; although the shuffle is in-place, returning the shuffled vector makes
Line 1,613 ⟶ 1,986:
v′
(check-true (derangement-of? #(11 12 13 14 15 16 17 18 19 20 21) v′)))</
{{out}}
Line 1,623 ⟶ 1,996:
This modifies the array passed as argument, in-place.
<syntaxhighlight lang="raku"
for reverse 1 .. @array.end -> $i {
my $j = (^$i).pick;
Line 1,634 ⟶ 2,007:
say @a;
sattolo-cycle(@a);
say @a;</
{{out|Sample output}}
Line 1,647 ⟶ 2,020:
The values of the array elements are specified via the command line (C.L.).
<
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,656 ⟶ 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. */</
{{out|output|text= when using the input of: [a null]}}
<pre>
Line 1,689 ⟶ 2,062:
=== version 2 ===
<
n=25
Do i=0 To n
Line 1,712 ⟶ 2,085:
End
Say ol
Return</
{{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,718 ⟶ 2,091:
=={{header|Ring}}==
<
# Project : Sattolo cycle
Line 1,742 ⟶ 2,115:
next
see nl
</syntaxhighlight>
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}}==
<
> class Array
> def sattolo_cycle!
Line 1,777 ⟶ 2,180:
[9, 8, 4, 2, 6, 1, 5, 10, 3, 7]
[9, 4, 2, 7, 6, 1, 10, 3, 8, 5]
=> 10</
=={{header|Run BASIC}}==
<
n = len(a$)
dim sit$(n) ' hold area to string
Line 1,807 ⟶ 2,210:
print
end sub
</
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}}==
<
scala.util.Random.shuffle(a)
a
}</
=={{header|SequenceL}}==
<syntaxhighlight lang="sequencel">
import <Utilities/Random.sl>;
import <Utilities/Sequence.sl>;
Line 1,834 ⟶ 2,237:
swapHelper(list(1), i(0), j(0), vali(0), valj(0)) := setElementAt(setElementAt(list, i, valj), j, vali);
</syntaxhighlight>
=={{header|Sidef}}==
Modifies the array in-place:
<
for i in (arr.len ^.. 1) {
arr.swap(i, i.irand)
}
}</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
sattoloCycle
Line 1,853 ⟶ 2,256:
b := Random between: a+1 and: self size.
self swap: a with: b]]
]</
Modifies the collection in-place. Collections that don't support that,
like strings, will throw an exception.
Use example:
<
()
st> #(10) copy sattoloCycle
Line 1,871 ⟶ 2,274:
(22 13 17 18 14 12 15 21 16 11 20 19 )
st> 'Sattolo cycle' asArray sattoloCycle asString
'yocS talcelto'</
=={{header|Swift}}==
<
public mutating func satalloShuffle() {
for i in stride(from: index(before: endIndex), through: 1, by: -1) {
Line 1,906 ⟶ 2,309:
print("\(testCase) shuffled = \(shuffled)")
}</
{{out}}
Line 1,914 ⟶ 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}}==
<
for (let i = items.length; i -= 1;) {
const j = Math.floor(Math.random() * i);
Line 1,923 ⟶ 2,369:
items[j] = tmp;
}
}</
=={{header|VBA}}==
<
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
Line 1,975 ⟶ 2,421:
For Each i In f: Debug.Print i;: Next i: Debug.Print
End Sub
</
After:
Before: 10
Line 1,990 ⟶ 2,436:
=={{header|Wren}}==
<
var rand = Random.new()
Line 2,011 ⟶ 2,457:
sattolo.call(test)
System.print("Sattolo : %(test)\n")
}</
{{out}}
Sample run:
<pre>
Original: []
Line 2,035 ⟶ 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}}==
<
local i, j, items$(1), n, t$
Line 2,061 ⟶ 2,554:
for n = 1 to 5
read item$ : print "[", sattolo$(item$), "]"
next</
=={{header|zkl}}==
<
foreach i in ([list.len()-1 .. 1,-1]){
list.swap(i,(0).random(i)); # 0 <= j < i
}
list
}</
<
sattoloCycle("this is a test".split()).println();</
{{out}}
<pre>
|