Sattolo cycle: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
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 72:
=={{header|Action!}}==
<
INT i
Line 115:
Test(a,3)
Test(b,12)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sattolo_cycle.png Screenshot from Atari 8-bit computer]
Line 137:
=={{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 161:
OD
END
</syntaxhighlight>
{{out}}
<pre>
Line 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 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 221:
set output to output as text
set AppleScript's text item delimiters to astid
return output</
{{output}}
Line 238:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 473:
</syntaxhighlight>
=={{header|Arturo}}==
<
if 2 > size arr -> return arr
lastIndex: (size arr)-1
Line 500:
loop lists 'l ->
print [l "->" cycle l]</
{{out}}
Line 511:
=={{header|AutoHotkey}}==
<
{
testCases:= [[]
Line 541:
}
}
</syntaxhighlight>
{{out}}
<pre>[]
Line 562:
=={{header|BaCon}}==
<
SUB Swap_Array(array[], total)
Line 587:
DECLARE demo5[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 }
Swap_Array(demo5, UBOUND(demo5))</
{{out}}
<pre>
Line 599:
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.
<
Swap ← {
i 𝕊 𝕩:
Line 614:
⟨10, 20, 30⟩
⟨11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22⟩
⟩</
'''Possible Output:'''
<
╵ ⟨⟩
⟨ 10 ⟩
Line 622:
⟨ 20 30 10 ⟩
⟨ 17 20 15 22 19 21 16 14 18 13 12 11 ⟩
┘</
=={{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 661:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 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 746:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 757:
=={{header|C sharp|C#}}==
<
void sattoloCycle<T>(IList<T> items) {
Line 766:
items[j] = tmp;
}
}</
=={{header|C++}}==
<
#include <ctime>
#include <string>
Line 817:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 837:
=={{header|D}}==
<
void main() {
Line 865:
assert(a != b, "An element stayed in place unexpectedly.");
}
}</
{{out}}
Line 876:
=={{header|EasyLang}}==
<syntaxhighlight lang="text">func sattolo_cycle . a[] .
for i = len a[] - 1 downto 1
r = random i
Line 884:
arr[] = [ 1 2 3 ]
call sattolo_cycle arr[]
print arr[] </
=={{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 901:
</pre>
=={{header|Factor}}==
<
random sequences ;
IN: rosetta-code.sattolo-cycle
Line 922:
[ "original: " write . ]
[ "cycled: " write sattolo . ] bi nl
] each</
{{out}}
<pre>
Line 942:
=={{header|Free Pascal}}==
<
{$ifdef fpc}{$mode delphi}{$endif}
uses math;
Line 960:
write(a[i]:4);
end;
end.</
<pre>
Output in Free Pascal:
Line 969:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,014:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>Starting array from 1 to 52
Line 1,023:
=={{header|Go}}==
<syntaxhighlight lang="go">
package main
Line 1,045:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,061:
=={{header|Haskell}}==
<
import Control.Monad.Primitive
import qualified Data.Vector as V
Line 1,097:
test [11..22 :: Int]
-- Also works for other types.
test "abcdef"</
{{out}}
Line 1,122:
Implementation:
<
for_i.}:i.-#y do.
j=.?i
Line 1,129:
y
)
</syntaxhighlight>
Example use:
<
sattolo ,10
Line 1,142:
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,154:
items[j] = tmp;
}
}</
=={{header|JavaScript}}==
<
for (var i = items.length-1; i > 0; i--) {
var j = Math.floor(Math.random() * i);
Line 1,164:
items[j] = tmp;
}
}</
=={{header|Jsish}}==
<
function sattoloCycle(items:array):void {
for (var i = items.length-1; i > 0; i--) {
Line 1,199:
a ==> [ 22, 11, 17, 15, 12, 14, 19, 13, 21, 18, 16, 20 ]
=!EXPECTEND!=
*/</
{{out}}
Line 1,218:
where program.jq is the following program:
<
def prns:
. as $n
Line 1,259:
| sattoloCycle;
task</
{{out}}
<pre>
Line 1,272:
{{works with|Julia|0.6}}
<
for i in last:-1:2
j = rand(1:i-1)
Line 1,283:
@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,292:
=={{header|Kotlin}}==
<
fun <T> sattolo(items: Array<T>) {
Line 1,308:
sattolo(items)
println(items.joinToString())
}</
Sample output:
{{out}}
Line 1,318:
=={{header|Lua}}==
<
local j
for i = #items, 2, -1 do
Line 1,337:
sattolo(array)
print("[" .. table.concat(array, ", ") .. "]")
end</
{{out}}
<pre>[]
Line 1,346:
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM RandomNumbers IMPORT Randomize,Random;
Line 1,380:
ReadChar
END SattoloCycle.</
=={{header|Nim}}==
{{trans|C}}
<
proc sattoloCycle[T](a: var openArray[T]) =
Line 1,412:
e.sattoloCycle()
echo "\nShuffled e = ", $e</
{{out}}
Line 1,427:
=={{header|Objeck}}==
{{trans|Objeck}}
<
function : Main(args : String[]) ~ Nil {
array := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Line 1,443:
}
}
</syntaxhighlight>
Output:
Line 1,451:
=={{header|Objective-C}}==
<
@interface NSMutableArray (SattoloCycle)
Line 1,463:
}
}
@end</
=={{header|OCaml}}==
<
for i = Array.length arr - 1 downto 1 do
let j = Random.int i in
Line 1,472:
arr.(i) <- arr.(j);
arr.(j) <- temp
done</
=={{header|Pascal}}==
Line 1,478:
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.
<
var
Line 1,523:
shuffle(sample3); printArray(sample3);
shuffle(sample4); printArray(sample4);
end.</
{{out}}
10
Line 1,531:
=={{header|Perl}}==
<
printf "%2d ", $_ for @a; print "\n";
Line 1,543:
@$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,549:
=={{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,562:
<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,571:
=={{header|PHP}}==
<
for ($i = 0; $i < count($items); $i++) {
$j = floor((mt_rand() / mt_getrandmax()) * $i);
Line 1,580:
return $items;
}
</syntaxhighlight>
=={{header|Picat}}==
<
Tests = [[],
[10],
Line 1,611:
T = L[I],
L[I] := L[J],
L[J] := T.</
{{out}}
Line 1,644:
=={{header|PicoLisp}}==
<
(de sattolo (Lst)
Line 1,654:
(println 'before L)
(sattolo L)
(println 'after L) )</
{{out}}
<pre>
Line 1,664:
<
>>> from random import randrange
>>> def sattoloCycle(items):
Line 1,689:
[2, 6, 5, 3, 9, 8, 10, 7, 1, 4]
[3, 6, 2, 5, 10, 4, 1, 9, 7, 8]
>>> </
=={{header|Quackery}}==
Line 1,695:
See [[Knuth shuffle#Quackery]] for notes re. the "in-place-ness" of this code.
<
2dup swap
temp share swap peek
Line 1,710:
[ dup size 1 - times
[ i 1+ dup random
rot [exch] ] ] is sattolo ( [ --> [ )</
{{Out}}
Line 1,750:
=={{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)
Line 1,769:
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,791:
=={{header|Racket}}==
<
;; although the shuffle is in-place, returning the shuffled vector makes
Line 1,824:
v′
(check-true (derangement-of? #(11 12 13 14 15 16 17 18 19 20 21) v′)))</
{{out}}
Line 1,834:
This modifies the array passed as argument, in-place.
<syntaxhighlight lang="raku"
for reverse 1 .. @array.end -> $i {
my $j = (^$i).pick;
Line 1,845:
say @a;
sattolo-cycle(@a);
say @a;</
{{out|Sample output}}
Line 1,858:
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,867:
$= /* [↓] 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,900:
=== version 2 ===
<
n=25
Do i=0 To n
Line 1,923:
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,929:
=={{header|Ring}}==
<
# Project : Sattolo cycle
Line 1,953:
next
see nl
</syntaxhighlight>
Output:
<pre>
Line 1,962:
=={{header|Ruby}}==
<
> class Array
> def sattolo_cycle!
Line 1,988:
[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 2,018:
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 2,045:
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 2,064:
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 2,082:
(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 2,117:
print("\(testCase) shuffled = \(shuffled)")
}</
{{out}}
Line 2,127:
=={{header|TypeScript}}==
<
for (let i = items.length; i -= 1;) {
const j = Math.floor(Math.random() * i);
Line 2,134:
items[j] = tmp;
}
}</
=={{header|VBA}}==
<
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
Line 2,186:
For Each i In f: Debug.Print i;: Next i: Debug.Print
End Sub
</
After:
Before: 10
Line 2,201:
=={{header|Wren}}==
<
var rand = Random.new()
Line 2,222:
sattolo.call(test)
System.print("Sattolo : %(test)\n")
}</
{{out}}
Line 2,249:
=={{header|XPL0}}==
<
int Array, Items, BytesPerItem;
int I, J;
Line 2,284:
[IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
]</
{{out}}
Line 2,295:
=={{header|Yabasic}}==
<
local i, j, items$(1), n, t$
Line 2,318:
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>
|