Generate random numbers without repeating a value: Difference between revisions

Line 165:
[19, 15, 10, 6, 17, 13, 14, 9, 2, 20, 3, 18, 8, 16, 7, 12, 1, 4, 5, 11]
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
In this entry, an external source of entropy is used to define a jq
filter, `prn_without_repetitions`, which generates a stream of
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".
<lang sh>
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq
</lang>
 
'''program.jq'''
<lang jq># Output: a prn in range(0;$n) except for $exceptions, where $n is . and $n > 0.
def prn($exceptions):
([range(0;.)] - $exceptions) as $available
| ($available|length) as $n
| def p:
if $n == 0 then "prn must have a non-empty pool from which to draw" | error
elif $n == 1 then $available[0]
else ([(($n-1)|tostring|length),1]|min) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then $available[.] else $n | p end
end;
p;
 
def prn_without_repetitions:
. as $n
| foreach range(0;$n) as $i ([];
. as $exceptions
| if length == $n then empty
else . + [($n|prn($exceptions))]
end;
.[-1]);
 
# The task:
(20 | prn_without_repetitions) + 1;</lang>
{{out}}
<pre>
4
11
3
8
1
9
16
6
5
7
12
17
15
19
10
20
18
2
13
14
</pre>
 
 
 
=={{header|Julia}}==
2,442

edits