Pick random element: Difference between revisions

No edit summary
Line 674:
<lang javascript>var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)];</lang>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
Neither jq nor gojq currently has a built-in PRNG, but it is quite straightforward
to define one if an external source of entropy is available. In this entry, `/dev/urandom`
is used like so:
<lang sh>< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq</lang>
 
<lang jq># Output: a prn in range(0;$n) where $n is `.`
def prn:
if . == 1 then 0
else . as $n
| ([1, (($n-1)|tostring|length)]|max) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
# An illustration - 10 selections at random with replacement:
range(0;10) | ["a", "b", "c"] | .[length|prn]</lang>
{{out}}
<pre>
bcbabacbbc
</pre>
 
=={{header|Julia}}==
2,503

edits