Generate random numbers without repeating a value: Difference between revisions
Generate random numbers without repeating a value (view source)
Revision as of 04:26, 6 September 2021
, 2 years ago→{{header|jq}}: Use Knuth shuffle
(→{{header|jq}}: simplify) |
(→{{header|jq}}: Use Knuth shuffle) |
||
Line 171:
In this entry, an external source of entropy is used to define a jq
filter, `knuthShuffle`, so that the specific task can then be accomplished using the expression:
<lang jq>[range(1;21)] | knuthShuffle</lang>
In the following, a bash or bash-like scripting environment is assumed, and the jq command is assumed to be "jq".
Line 181 ⟶ 178:
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq
</lang>
'''program.jq'''▼
if . == 1 then 0
else . as $n▼
| [limit($w; inputs)] | join("") | tonumber
def knuthShuffle:
▲'''program.jq'''
▲<lang jq># Output: a prn in range(0;$n) except for $exceptions, where $n is . and $n > 0.
| if $n <= 1 then .
else {i: $n, a: .}
| until(.i == 0;
▲ | ($available|length) as $n
▲ | def p:
| (.i + 1 | prn) as $j
| .a[.i] = .a[$j]
▲ else ([(($n-1)|tostring|length),1]|min) as $w
| .a[
| .a
▲ | if . < $n then $available[.] else $n | p end
end;
▲ p;
▲ . as $n
▲ .[-1]);
# The task:
[range(
{{out}}
<pre>
|