Generate random numbers without repeating a value: Difference between revisions
Content added Content deleted
(→{{header|jq}}: simplify) |
(→{{header|jq}}: Use Knuth shuffle) |
||
Line 171: | Line 171: | ||
In this entry, an external source of entropy is used to define a jq |
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: |
|||
filter, `prn_without_repetitions`, which generates a stream of |
|||
<lang jq>[range(1;21)] | knuthShuffle</lang> |
|||
pseudo-random numbers in the range 0 up to but excluding a specified |
|||
value. The specific task can then be expressed as: |
|||
<lang jq>(19 | prn_without_repetitions) + 1 |
|||
</lang> |
|||
In the following, a bash or bash-like scripting environment is assumed, and the jq command is assumed to be "jq". |
In the following, a bash or bash-like scripting environment is assumed, and the jq command is assumed to be "jq". |
||
Line 181: | Line 178: | ||
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq |
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq |
||
</lang> |
</lang> |
||
⚫ | |||
⚫ | |||
⚫ | |||
if . == 1 then 0 |
|||
⚫ | |||
⚫ | |||
| [limit($w; inputs)] | join("") | tonumber |
|||
⚫ | |||
⚫ | |||
def knuthShuffle: |
|||
⚫ | |||
⚫ | |||
⚫ | |||
| if $n <= 1 then . |
|||
def prn($exceptions): |
|||
else {i: $n, a: .} |
|||
([range(0;.)] - $exceptions) as $available |
|||
| until(.i == 0; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
| (.i + 1 | prn) as $j |
|||
if $n == 0 then "prn must have a non-empty pool from which to draw" | error |
|||
| .a[.i] as $t |
|||
| .a[.i] = .a[$j] |
|||
⚫ | |||
| [ |
| .a[$j] = $t) |
||
| .a |
|||
⚫ | |||
end; |
end; |
||
⚫ | |||
# Output: a stream |
|||
def prn_without_repetitions: |
|||
⚫ | |||
| foreach range(0;$n) as $i ([]; |
|||
. as $exceptions |
|||
| . + [$n|prn($exceptions)]; |
|||
⚫ | |||
# The task: |
# The task: |
||
( |
[range(1;21)] | knuthShuffle</lang> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |