Sattolo cycle: Difference between revisions

(Simplified the proc by removing a useless test.)
Line 1,050:
<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:
<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,
{{out}}
<pre>
./rc-knuth-shuffle.sh
[]
[20,10]
[20,30,10]
[17,13,14,15,20,21,19,16,18,22,12,11]
</pre>
 
 
=={{header|Julia}}==
2,479

edits