Generate random numbers without repeating a value: Difference between revisions
No edit summary |
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
||
Line 22: | Line 22: | ||
{{trans|Nim}} |
{{trans|Nim}} |
||
< |
<syntaxhighlight lang="11l">F generate(a, b) |
||
[Int] result |
[Int] result |
||
V count = b - a + 1 |
V count = b - a + 1 |
||
Line 36: | Line 36: | ||
L 5 |
L 5 |
||
print(generate(1, 20))</ |
print(generate(1, 20))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 48: | Line 48: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC PrintTable(BYTE ARRAY tab BYTE size) |
||
BYTE i |
BYTE i |
||
Line 86: | Line 86: | ||
PrintTable(tab,LEN) |
PrintTable(tab,LEN) |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Generate_random_numbers_without_repeating_a_value.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Generate_random_numbers_without_repeating_a_value.png Screenshot from Atari 8-bit computer] |
||
Line 105: | Line 105: | ||
{{libheader|ALGOL 68-rows}} |
{{libheader|ALGOL 68-rows}} |
||
This is vertually identical to the Algol 68 sample for the Knuth Shuffle Task. |
This is vertually identical to the Algol 68 sample for the Knuth Shuffle Task. |
||
< |
<syntaxhighlight lang="algol68"># generate a set of 20 random integers without duplicates # |
||
# same as the Knuth Shuffle sample, but with different display # |
# same as the Knuth Shuffle sample, but with different display # |
||
Line 129: | Line 129: | ||
knuth shuffle(a); |
knuth shuffle(a); |
||
SHOW a |
SHOW a |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 136: | Line 136: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">-- Return a script object containing: 1) a list of all the integers in the required range and |
||
-- 2) a handler that returns one of them at random without repeating any previous choices. |
-- 2) a handler that returns one of them at random without repeating any previous choices. |
||
-- Calls to the handler after all the numbers have been used just return 'missing value'. |
-- Calls to the handler after all the numbers have been used just return 'missing value'. |
||
Line 175: | Line 175: | ||
end task |
end task |
||
task()</ |
task()</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
< |
<syntaxhighlight lang="applescript">{16, 9, 12, 6, 17, 10, 1, 5, 3, 2, 7, 20, 14, 18, 19, 11, 15, 13, 8, 4}</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">generateUniqueRandoms: function [][ |
||
result: new [] |
result: new [] |
||
Line 195: | Line 195: | ||
loop 3 'x [ |
loop 3 'x [ |
||
print generateUniqueRandoms |
print generateUniqueRandoms |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 204: | Line 204: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f GENERATE_RANDOM_NUMBERS_WITHOUT_REPEATING_A_VALUE.AWK |
# syntax: GAWK -f GENERATE_RANDOM_NUMBERS_WITHOUT_REPEATING_A_VALUE.AWK |
||
BEGIN { |
BEGIN { |
||
Line 221: | Line 221: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 230: | Line 230: | ||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="basic256">arraybase 1 |
||
for num = 1 to 5 |
for num = 1 to 5 |
||
call pRand() |
call pRand() |
||
Line 252: | Line 252: | ||
until nr = 21 |
until nr = 21 |
||
print |
print |
||
end subroutine</ |
end subroutine</syntaxhighlight> |
||
==={{header|QBasic}}=== |
==={{header|QBasic}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="qbasic">DECLARE SUB pRand () |
||
RANDOMIZE TIMER |
RANDOMIZE TIMER |
||
Line 279: | Line 279: | ||
LOOP UNTIL nr = 21 |
LOOP UNTIL nr = 21 |
||
PRINT |
PRINT |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
// Generate random numbers without repeating a value. Nigel Galloway: August 27th., 2021 |
// Generate random numbers without repeating a value. Nigel Galloway: August 27th., 2021 |
||
MathNet.Numerics.Combinatorics.GeneratePermutation 20|>Array.map((+)1)|>Array.iter(printf "%d "); printfn "" |
MathNet.Numerics.Combinatorics.GeneratePermutation 20|>Array.map((+)1)|>Array.iter(printf "%d "); printfn "" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 294: | Line 294: | ||
Generating a random permutation of 1..20: |
Generating a random permutation of 1..20: |
||
{{works with|Factor|0.99 2021-06-02}} |
{{works with|Factor|0.99 2021-06-02}} |
||
< |
<syntaxhighlight lang="factor">USING: kernel math.combinatorics math.ranges prettyprint random |
||
sequences ; |
sequences ; |
||
Line 300: | Line 300: | ||
[ length dup nPk random ] keep permutation ; |
[ length dup nPk random ] keep permutation ; |
||
20 [1,b] random-permutation .</ |
20 [1,b] random-permutation .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 307: | Line 307: | ||
Shuffling 1..20: |
Shuffling 1..20: |
||
{{works with|Factor|0.99 2021-06-02}} |
{{works with|Factor|0.99 2021-06-02}} |
||
< |
<syntaxhighlight lang="factor">USING: math.ranges prettyprint random vectors ; |
||
20 [1,b] >vector randomize .</ |
20 [1,b] >vector randomize .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 316: | Line 316: | ||
Sampling 20 elements from 1..20: |
Sampling 20 elements from 1..20: |
||
{{works with|Factor|0.99 2021-06-02}} |
{{works with|Factor|0.99 2021-06-02}} |
||
< |
<syntaxhighlight lang="factor">USING: math.ranges prettyprint random ; |
||
20 [1,b] 20 sample .</ |
20 [1,b] 20 sample .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 326: | Line 326: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">Sub pRand |
||
Dim As Integer randCheck(20), nr = 1 |
Dim As Integer randCheck(20), nr = 1 |
||
Do |
Do |
||
Line 347: | Line 347: | ||
pRand() |
pRand() |
||
Next num |
Next num |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 361: | Line 361: | ||
{{trans|Nim}} |
{{trans|Nim}} |
||
This uses Go's 'native' random number generator which internally uses a custom algorithm attributed to D P Mitchell and J A Reeds and can generate non-negative random integers in the 64-bit range. |
This uses Go's 'native' random number generator which internally uses a custom algorithm attributed to D P Mitchell and J A Reeds and can generate non-negative random integers in the 64-bit range. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 398: | Line 398: | ||
generate(1, 20) |
generate(1, 20) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 411: | Line 411: | ||
<br> |
<br> |
||
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Go has a standard library function for this which uses the Fisher-Yates (aka Knuth) shuffle. |
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Go has a standard library function for this which uses the Fisher-Yates (aka Knuth) shuffle. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 432: | Line 432: | ||
fmt.Println(s[1 : len(s)-2]) |
fmt.Println(s[1 : len(s)-2]) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 444: | Line 444: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Data.List (sortBy) |
||
import Data.Ord (comparing) |
import Data.Ord (comparing) |
||
import System.Random (newStdGen, randomRs) |
import System.Random (newStdGen, randomRs) |
||
Line 459: | Line 459: | ||
main = |
main = |
||
inRandomOrder [1 .. 20] |
inRandomOrder [1 .. 20] |
||
>>= print</ |
>>= print</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
For example: |
For example: |
||
Line 465: | Line 465: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">import java.util.*; |
||
public class RandomShuffle { |
public class RandomShuffle { |
||
Line 476: | Line 476: | ||
System.out.println(list); |
System.out.println(list); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 485: | Line 485: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
"use strict"; |
"use strict"; |
||
Line 540: | Line 540: | ||
// MAIN --- |
// MAIN --- |
||
return JSON.stringify(main()); |
return JSON.stringify(main()); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
For example: |
For example: |
||
Line 551: | Line 551: | ||
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, `knuthShuffle`, so that the specific task can then be accomplished using the expression: |
||
< |
<syntaxhighlight lang="jq">[range(1;21)] | knuthShuffle</syntaxhighlight> |
||
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". |
||
<syntaxhighlight lang="sh"> |
|||
<lang sh> |
|||
< /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 |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''program.jq''' |
'''program.jq''' |
||
< |
<syntaxhighlight lang="jq"># Output: a prn in range(0;$n) where $n is `.` |
||
def prn: |
def prn: |
||
if . == 1 then 0 |
if . == 1 then 0 |
||
Line 581: | Line 581: | ||
# The task: |
# The task: |
||
[range(1;21)] | knuthShuffle</ |
[range(1;21)] | knuthShuffle</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 608: | Line 608: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Julia's Random module contains a function called `randperm(n::Integer)` which constructs a random permutation of integers from 1 to n. |
Julia's Random module contains a function called `randperm(n::Integer)` which constructs a random permutation of integers from 1 to n. |
||
< |
<syntaxhighlight lang="julia">using Random |
||
@show randperm(20) |
@show randperm(20) |
||
</ |
</syntaxhighlight>{{out}} |
||
<pre> |
<pre> |
||
randperm(20) = [20, 2, 5, 6, 18, 14, 12,4, 13, 7, 15, 3, 19, 17, 1, 9, 16, 11, 10] |
randperm(20) = [20, 2, 5, 6, 18, 14, 12,4, 13, 7, 15, 3, 19, 17, 1, 9, 16, 11, 10] |
||
</pre> |
</pre> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
<lang |
<syntaxhighlight lang="mathematica">RandomSample[Range@20]</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
Line 627: | Line 627: | ||
Here, we have defined a procedure which accepts a slice <code>a..b</code> as argument and returns a shuffled sequence of values from a to b. It uses the same algorithm as in Wren solution, i.e. a list to keep track of generated values. |
Here, we have defined a procedure which accepts a slice <code>a..b</code> as argument and returns a shuffled sequence of values from a to b. It uses the same algorithm as in Wren solution, i.e. a list to keep track of generated values. |
||
< |
<syntaxhighlight lang="nim">import random |
||
randomize() |
randomize() |
||
Line 643: | Line 643: | ||
for i in 1..5: |
for i in 1..5: |
||
echo generate(1..20)</ |
echo generate(1..20)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 654: | Line 654: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Just shuffle... |
Just shuffle... |
||
< |
<syntaxhighlight lang="perl">#!/usr/bin/perl |
||
use strict; # https://rosettacode.org/wiki/Generate_random_numbers_without_repeating_a_value |
use strict; # https://rosettacode.org/wiki/Generate_random_numbers_without_repeating_a_value |
||
Line 660: | Line 660: | ||
use List::Util qw( shuffle ); |
use List::Util qw( shuffle ); |
||
print "@{[ shuffle 1 .. 20 ]}\n" for 1 .. 5;</ |
print "@{[ shuffle 1 .. 20 ]}\n" for 1 .. 5;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 673: | Line 673: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Trival use of standard builtins. Progressively filtering the output of rand(20) would gain nothing except wasted cycles. Normally I would use "with javascript_semantics", or equivalently just "with js", to explicitly specify/verify the code can be run on both the desktop ''and'' in a web browser, however here that somehow seems like overkill. |
Trival use of standard builtins. Progressively filtering the output of rand(20) would gain nothing except wasted cycles. Normally I would use "with javascript_semantics", or equivalently just "with js", to explicitly specify/verify the code can be run on both the desktop ''and'' in a web browser, however here that somehow seems like overkill. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">))</span> |
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">))</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 682: | Line 682: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python"> |
||
import random |
import random |
||
print(random.sample(range(1, 21), 20)) |
print(random.sample(range(1, 21), 20)) |
||
</ |
</syntaxhighlight>{{out}}[14, 15, 3, 18, 4, 11, 16, 10, 12, 20, 13, 1, 6, 7, 2, 17, 5, 9, 19, 8] |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 711: | Line 711: | ||
=={{header|R}}== |
=={{header|R}}== |
||
R makes this so easy that it feels like you've missed the point. |
R makes this so easy that it feels like you've missed the point. |
||
<lang |
<syntaxhighlight lang="rsplus">sample(20)</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Raku has three distinct "random" functions built in. rand() for when you want some fraction between 0 and 1. roll() when you want to select elements from a collection with replacement (rolls of a die). And pick() for when you want to select some elements from a collection ''without'' replacement. (pick a card, any card, or two cards or 10 cards...). If you want to select ''all'' the elements in random order, just pick 'whatever'. Here we'll pick all from 1 to 20, 5 times using the repetition operator. |
Raku has three distinct "random" functions built in. rand() for when you want some fraction between 0 and 1. roll() when you want to select elements from a collection with replacement (rolls of a die). And pick() for when you want to select some elements from a collection ''without'' replacement. (pick a card, any card, or two cards or 10 cards...). If you want to select ''all'' the elements in random order, just pick 'whatever'. Here we'll pick all from 1 to 20, 5 times using the repetition operator. |
||
<lang |
<syntaxhighlight lang="raku" line>.put for (1..20).pick(*) xx 5</syntaxhighlight> |
||
{{out|Sample output}} |
{{out|Sample output}} |
||
<pre>20 4 5 7 15 19 2 16 8 6 3 12 14 13 10 18 9 17 1 11 |
<pre>20 4 5 7 15 19 2 16 8 6 3 12 14 13 10 18 9 17 1 11 |
||
Line 732: | Line 732: | ||
With the method/algorithm used herein, there are no random numbers being discarded (due to possible |
With the method/algorithm used herein, there are no random numbers being discarded (due to possible |
||
<br>duplicates) because there cannot ''be'' any duplicates. |
<br>duplicates) because there cannot ''be'' any duplicates. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program generates & displays a list of random integers (1 ──► N) with no repeats.*/ |
||
parse arg n cols seed . /*obtain optional argument from the CL.*/ |
parse arg n cols seed . /*obtain optional argument from the CL.*/ |
||
if n=='' | n=="," then n= 20 /*Not specified? Then use the default.*/ |
if n=='' | n=="," then n= 20 /*Not specified? Then use the default.*/ |
||
Line 759: | Line 759: | ||
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible show residual output.*/ |
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible show residual output.*/ |
||
say '───────┴'center("" , 1 + cols*(w+1), '─'); say |
say '───────┴'center("" , 1 + cols*(w+1), '─'); say |
||
exit 0 /*stick a fork in it, we're all done. */</ |
exit 0 /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
{{out|output|text= when using the default inputs:}} |
{{out|output|text= when using the default inputs:}} |
||
<pre> |
<pre> |
||
Line 769: | Line 769: | ||
</pre> |
</pre> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
see "working..." + nl |
see "working..." + nl |
||
decimals(3) |
decimals(3) |
||
Line 803: | Line 803: | ||
ok |
ok |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 817: | Line 817: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">nums = (1..20).to_a |
||
5.times{ puts nums.shuffle.join(" ") }</ |
5.times{ puts nums.shuffle.join(" ") }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>2 9 19 12 7 18 17 13 5 6 20 10 14 4 1 8 11 15 3 16 |
<pre>2 9 19 12 7 18 17 13 5 6 20 10 14 4 1 8 11 15 3 16 |
||
Line 827: | Line 827: | ||
</pre> |
</pre> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">// [dependencies] |
||
// rand = "0.7.2" |
// rand = "0.7.2" |
||
Line 837: | Line 837: | ||
v.shuffle(&mut rng); |
v.shuffle(&mut rng); |
||
println!("{:?}", v); |
println!("{:?}", v); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 846: | Line 846: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="ruby">var nums = (1..20).to_a |
||
5.times{ say nums.shuffle.join(" ") }</ |
5.times{ say nums.shuffle.join(" ") }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 859: | Line 859: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">var array = Array(1...20) |
||
array.shuffle() |
array.shuffle() |
||
print(array)</ |
print(array)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 870: | Line 870: | ||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
{{trans|go}} |
{{trans|go}} |
||
< |
<syntaxhighlight lang="vlang">import rand |
||
import rand.seed |
import rand.seed |
||
Line 897: | Line 897: | ||
generate(1, 20) |
generate(1, 20) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Same as Go entry</pre> |
<pre>Same as Go entry</pre> |
||
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Vlang has a standard library function for this which uses the Fisher-Yates (aka Knuth) shuffle. |
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Vlang has a standard library function for this which uses the Fisher-Yates (aka Knuth) shuffle. |
||
< |
<syntaxhighlight lang="vlang">import rand |
||
import rand.seed |
import rand.seed |
||
Line 914: | Line 914: | ||
println(s[1 .. s.len-2]) |
println(s[1 .. s.len-2]) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 924: | Line 924: | ||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
This uses Wren's 'native' pseudo-random number generator which internally uses WELL512a and can generate random integers in the 32-bit range. |
This uses Wren's 'native' pseudo-random number generator which internally uses WELL512a and can generate random integers in the 32-bit range. |
||
< |
<syntaxhighlight lang="ecmascript">import "random" for Random |
||
import "/fmt" for Fmt |
import "/fmt" for Fmt |
||
Line 944: | Line 944: | ||
// generate 5 sets say |
// generate 5 sets say |
||
for (i in 1..5) generate.call(1..20)</ |
for (i in 1..5) generate.call(1..20)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 957: | Line 957: | ||
<br> |
<br> |
||
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Wren has a built-in function for this which uses the Fisher-Yates (aka Knuth) shuffle. |
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Wren has a built-in function for this which uses the Fisher-Yates (aka Knuth) shuffle. |
||
< |
<syntaxhighlight lang="ecmascript">import "random" for Random |
||
import "/fmt" for Fmt |
import "/fmt" for Fmt |
||
Line 965: | Line 965: | ||
rand.shuffle(numbers) |
rand.shuffle(numbers) |
||
Fmt.print("$2d", numbers) |
Fmt.print("$2d", numbers) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 977: | Line 977: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">int Set, R; |
||
[Set:= 0; |
[Set:= 0; |
||
repeat R:= Ran(20); |
repeat R:= Ran(20); |
||
Line 984: | Line 984: | ||
IntOut(0, R+1); ChOut(0, ^ )]; |
IntOut(0, R+1); ChOut(0, ^ )]; |
||
until Set = $F_FFFF; |
until Set = $F_FFFF; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
Revision as of 14:06, 27 August 2022
Many puzzle games such as the 15 puzzle game need a way to randomize the order of the pieces. One way to do this is to create an array and fill it with random values, with each element's index in that array being its position. Unfortunately, most random number generators can produce the same value more than once, which in this case isn't what we want.
- Task
Create a random number generator and have it output the numbers 1 through 20 (inclusive), in a random order. It cannot produce the same value more than once.
- Or
Given the output of an existing random number generator that does produce repeated output, create a function that constrains the output to numbers 1 through 20 (inclusive), and no number is output more than once. (Technically it stops being "random" at that point, but that's beyond the scope of this task.) Try your best not to make the process take too long at runtime.
For the second version of the task, the random number generator itself need not be implemented; however you must specify its possible range of values before your constraint function is applied. (e.g "Assume the random number generator creates a value from 0 to 255, and values are allowed to repeat")
- Related Tasks
11l
F generate(a, b)
[Int] result
V count = b - a + 1
V generated = [0B] * count
L
V n = random:(a .. b)
I !generated[n - a]
generated[n - a] = 1B
result.append(n)
I --count == 0
L.break
R result
L 5
print(generate(1, 20))
- Output:
[5, 6, 17, 14, 8, 13, 7, 11, 12, 16, 15, 18, 1, 9, 20, 10, 3, 4, 2, 19] [9, 1, 13, 10, 4, 17, 3, 6, 5, 16, 18, 7, 19, 20, 12, 8, 2, 11, 14, 15] [14, 10, 7, 4, 5, 12, 11, 18, 19, 6, 9, 13, 20, 16, 17, 15, 1, 3, 8, 2] [9, 3, 20, 15, 5, 19, 18, 1, 4, 16, 12, 2, 8, 17, 6, 13, 14, 7, 10, 11] [8, 13, 19, 4, 16, 5, 18, 2, 7, 20, 12, 9, 10, 15, 11, 3, 17, 1, 6, 14]
Action!
PROC PrintTable(BYTE ARRAY tab BYTE size)
BYTE i
FOR i=0 TO size-1
DO
PrintF("%B ",tab(i))
OD
PutE() PutE()
RETURN
PROC KnuthShuffle(BYTE ARRAY tab BYTE size)
BYTE i,j,tmp
i=size-1
WHILE i>0
DO
j=Rand(i)
tmp=tab(i)
tab(i)=tab(j)
tab(j)=tmp
i==-1
OD
RETURN
PROC Main()
DEFINE LEN="20"
BYTE ARRAY tab(LEN)
BYTE i
FOR i=1 TO LEN
DO
tab(i-1)=i
OD
FOR i=1 TO 5
DO
KnuthShuffle(tab,LEN)
PrintTable(tab,LEN)
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
17 6 20 3 8 10 14 12 4 15 2 7 16 18 15 19 9 13 11 6 8 1 10 5 20 16 14 3 12 13 2 17 11 9 4 7 19 18 15 3 15 13 8 19 5 10 1 17 20 16 4 2 6 14 7 18 11 9 12 19 16 15 9 4 14 20 2 11 12 3 6 8 17 15 10 18 13 7 14 2 1 18 10 7 13 11 17 4 20 9 6 3 16 19 5 15 12 8
ALGOL 68
This is vertually identical to the Algol 68 sample for the Knuth Shuffle Task.
# generate a set of 20 random integers without duplicates #
# same as the Knuth Shuffle sample, but with different display #
PR read "rows.incl.a68" PR # include array related utilities #
PROC between = (INT a, b)INT :
(
ENTIER (random * ABS (b-a+1) + (a<b|a|b))
);
PROC knuth shuffle = (REF[]INT a)VOID:
(
FOR i FROM LWB a TO UPB a DO
INT j = between(LWB a, UPB a);
INT t = a[i];
a[i] := a[j];
a[j] := t
OD
);
main:(
[20]INT a;
FOR i FROM 1 TO 20 DO a[i] := i OD;
knuth shuffle(a);
SHOW a
)
- Output:
17 6 11 5 7 15 18 8 4 3 10 13 9 2 12 1 19 14 20 16
AppleScript
-- Return a script object containing: 1) a list of all the integers in the required range and
-- 2) a handler that returns one of them at random without repeating any previous choices.
-- Calls to the handler after all the numbers have been used just return 'missing value'.
on makeRNG(low, high)
script RNG
property indexShift : missing value
property ints : {}
on nextInt()
try
set n to some number of my ints
set item (n + indexShift) of my ints to missing value
on error number -1728
set n to missing value
end try
return n
end nextInt
end script
if (low > high) then set {low, high} to {high, low}
set RNG's indexShift to 1 - low
repeat with n from low to high
set end of RNG's ints to n
end repeat
return RNG
end makeRNG
on task()
set low to 1
set high to 20
set generator to makeRNG(low, high)
set output to {}
repeat (high - low + 1) times
set end of output to generator's nextInt()
end repeat
return output
end task
task()
- Output:
{16, 9, 12, 6, 17, 10, 1, 5, 3, 2, 7, 20, 14, 18, 19, 11, 15, 13, 8, 4}
Arturo
generateUniqueRandoms: function [][
result: new []
while [20 > size result][
rand: sample 1..20
if not? in? rand result ->
'result ++ rand
]
return result
]
loop 3 'x [
print generateUniqueRandoms
]
- Output:
16 6 1 4 7 18 19 3 9 10 12 5 8 15 14 17 11 13 20 2 12 16 3 7 4 15 6 14 19 13 10 8 11 2 17 5 9 18 20 1 5 6 18 12 4 3 19 14 13 11 2 7 17 9 10 8 20 16 1 15
AWK
# syntax: GAWK -f GENERATE_RANDOM_NUMBERS_WITHOUT_REPEATING_A_VALUE.AWK
BEGIN {
limit = 20
srand()
printf("range 1-%d:",limit)
while (count < limit) {
n = sprintf("%d",int(rand()*limit)+1)
if (!(n in arr)) {
printf(" %d",n)
arr[n] = ""
count++
}
}
printf("\n")
exit(0)
}
- Output:
range 1-20: 16 18 15 4 13 6 11 2 1 20 14 3 7 19 17 12 10 9 5 8
BASIC
BASIC256
arraybase 1
for num = 1 to 5
call pRand()
next num
end
subroutine pRand()
dim randCheck(21)
nr = 1
do
aleat = int(rand * 20) + 1
if randCheck[aleat] = 1 then
continue do
else
randCheck[aleat] = 1
print aleat; " ";
end if
for n = 1 to randCheck[?]
if randCheck[nr] then nr += 1
next n
until nr = 21
print
end subroutine
QBasic
DECLARE SUB pRand ()
RANDOMIZE TIMER
FOR num = 1 TO 5
pRand
NEXT num
END
SUB pRand
DIM randCheck(1 TO 21)
nr = 1
DO
aleat = INT(RND * 20) + 1
IF randCheck(aleat) <> 1 THEN
randCheck(aleat) = 1
PRINT aleat;
END IF
FOR n = 1 TO UBOUND(randCheck)
IF randCheck(nr) = 1 THEN nr = nr + 1
NEXT n
LOOP UNTIL nr = 21
PRINT
END SUB
F#
// Generate random numbers without repeating a value. Nigel Galloway: August 27th., 2021
MathNet.Numerics.Combinatorics.GeneratePermutation 20|>Array.map((+)1)|>Array.iter(printf "%d "); printfn ""
- Output:
12 7 17 8 10 13 16 19 20 14 18 5 9 11 3 4 1 15 6 2
Factor
Generating a random permutation of 1..20:
USING: kernel math.combinatorics math.ranges prettyprint random
sequences ;
: random-permutation ( seq -- newseq )
[ length dup nPk random ] keep permutation ;
20 [1,b] random-permutation .
- Output:
{ 7 10 12 9 5 8 20 14 18 4 13 3 17 16 19 6 15 1 2 11 }
Shuffling 1..20:
USING: math.ranges prettyprint random vectors ;
20 [1,b] >vector randomize .
- Output:
V{ 20 7 8 17 18 1 15 13 12 10 3 14 19 2 5 9 16 11 6 4 }
Sampling 20 elements from 1..20:
USING: math.ranges prettyprint random ;
20 [1,b] 20 sample .
- Output:
{ 12 3 16 13 1 9 8 11 5 19 15 18 17 20 10 4 7 14 6 2 }
FreeBASIC
Sub pRand
Dim As Integer randCheck(20), nr = 1
Do
Dim As Integer aleat = Int(Rnd * 20) + 1
If randCheck(aleat) = 1 Then
Continue Do
Else
randCheck(aleat) = 1
Print aleat;
End If
For n As Integer = 1 To Ubound(randCheck)
If randCheck(nr) = 1 Then nr += 1
Next n
Loop Until nr = 21
Print
End Sub
Randomize Timer
For num As Integer = 1 To 5
pRand()
Next num
Sleep
- Output:
7 11 16 13 14 6 20 2 1 10 17 18 9 12 4 8 15 19 5 3 9 6 18 16 3 14 1 8 11 2 7 20 4 13 19 12 17 5 15 10 11 19 15 6 10 17 13 8 18 2 12 14 16 5 4 1 3 9 7 20 5 18 13 8 4 15 16 12 7 6 1 19 2 17 9 14 10 20 3 11 19 5 4 9 12 11 8 14 6 13 3 1 7 2 16 18 10 17 20 15
Go
This uses Go's 'native' random number generator which internally uses a custom algorithm attributed to D P Mitchell and J A Reeds and can generate non-negative random integers in the 64-bit range.
package main
import (
"fmt"
"log"
"math/rand"
"time"
)
// Generates and prints all numbers within an inclusive range whose endpoints are
// non-negative 64-bit integers. The numbers are generated in random order with
// any repetitions being ignored.
func generate(from, to int64) {
if to < from || from < 0 {
log.Fatal("Invalid range.")
}
span := to - from + 1
generated := make([]bool, span) // all false by default, zero indexing
count := span
for count > 0 {
n := from + rand.Int63n(span) // upper endpoint is exclusive
if !generated[n-from] {
generated[n-from] = true
fmt.Printf("%2d ", n)
count--
}
}
fmt.Println()
}
func main() {
rand.Seed(time.Now().UnixNano())
// generate 5 sets say
for i := 1; i <= 5; i++ {
generate(1, 20)
}
}
- Output:
Sample run:
16 7 5 11 10 12 1 19 9 2 4 14 6 18 17 8 20 3 13 15 10 3 5 7 14 9 20 6 11 8 13 18 1 17 15 12 4 2 16 19 12 14 16 11 15 2 8 13 3 19 6 17 18 4 10 5 20 1 7 9 4 11 9 17 14 16 2 7 6 1 12 20 8 15 5 13 10 18 19 3 19 13 9 7 5 12 11 17 1 3 16 4 15 14 20 8 6 18 2 10
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Go has a standard library function for this which uses the Fisher-Yates (aka Knuth) shuffle.
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
numbers := make([]int, 20)
for i := 0; i < 20; i++ {
numbers[i] = i + 1
}
for i := 1; i <= 5; i++ {
rand.Shuffle(20, func(i, j int) {
numbers[i], numbers[j] = numbers[j], numbers[i]
})
s := fmt.Sprintf("%2d ", numbers)
fmt.Println(s[1 : len(s)-2])
}
}
- Output:
13 10 18 7 3 5 17 4 1 11 16 20 9 12 14 2 15 19 6 8 19 12 11 1 3 14 7 20 2 18 4 10 9 5 8 6 15 13 16 17 10 6 11 3 5 13 15 4 16 12 1 14 20 7 2 19 8 17 9 18 4 14 17 15 1 6 12 11 2 3 19 10 9 18 7 13 8 20 16 5 13 12 8 3 9 17 14 10 6 2 11 20 19 18 4 7 16 1 15 5
Haskell
import Data.List (sortBy)
import Data.Ord (comparing)
import System.Random (newStdGen, randomRs)
--------------------- IN RANDOM ORDER --------------------
inRandomOrder :: [a] -> IO [a]
inRandomOrder xs =
fmap fst . sortBy (comparing snd) . zip xs
<$> (randomRs (0, 1) <$> newStdGen :: IO [Double])
--------------------------- TEST -------------------------
main :: IO ()
main =
inRandomOrder [1 .. 20]
>>= print
- Output:
For example:
[16,1,3,9,8,20,12,18,11,19,2,14,5,6,13,15,17,10,7,4]
Java
import java.util.*;
public class RandomShuffle {
public static void main(String[] args) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
for (int j = 1; j <= 20; ++j)
list.add(j);
Collections.shuffle(list, rand);
System.out.println(list);
}
}
- Output:
[19, 15, 10, 6, 17, 13, 14, 9, 2, 20, 3, 18, 8, 16, 7, 12, 1, 4, 5, 11]
JavaScript
(() => {
"use strict";
// ---------- NON-REPEATING RANDOM NUMBERS -----------
// main :: IO ()
const main = () =>
sortOn(Math.random)(
enumFromTo(1)(20)
);
// --------------------- GENERIC ---------------------
// comparing :: (a -> b) -> (a -> a -> Ordering)
const comparing = f =>
// The ordering of f(x) and f(y) as a value
// drawn from {-1, 0, 1}, representing {LT, EQ, GT}.
x => y => {
const
a = f(x),
b = f(y);
return a < b ? -1 : (a > b ? 1 : 0);
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// sortBy :: (a -> a -> Ordering) -> [a] -> [a]
const sortBy = f =>
// A copy of xs sorted by the comparator function f.
xs => xs.slice()
.sort((a, b) => f(a)(b));
// sortOn :: Ord b => (a -> b) -> [a] -> [a]
const sortOn = f =>
// Equivalent to sortBy(comparing(f)), but with f(x)
// evaluated only once for each x in xs.
// ('Schwartzian' decorate-sort-undecorate).
xs => sortBy(
comparing(x => x[0])
)(
xs.map(x => [f(x), x])
)
.map(x => x[1]);
// MAIN ---
return JSON.stringify(main());
})();
- Output:
For example:
[6,9,8,16,5,15,19,7,13,12,4,20,1,2,18,11,14,17,10,3]
jq
Works with gojq, the Go implementation of 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:
[range(1;21)] | knuthShuffle
In the following, a bash or bash-like scripting environment is assumed, and the jq command is assumed to be "jq".
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq
program.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;
def knuthShuffle:
length as $n
| if $n <= 1 then .
else {i: $n, a: .}
| until(.i == 0;
.i += -1
| (.i + 1 | prn) as $j
| .a[.i] as $t
| .a[.i] = .a[$j]
| .a[$j] = $t)
| .a
end;
# The task:
[range(1;21)] | knuthShuffle
- Output:
4 11 3 8 1 9 16 6 5 7 12 17 15 19 10 20 18 2 13 14
Julia
Julia's Random module contains a function called `randperm(n::Integer)` which constructs a random permutation of integers from 1 to n.
using Random
@show randperm(20)
- Output:
randperm(20) = [20, 2, 5, 6, 18, 14, 12,4, 13, 7, 15, 3, 19, 17, 1, 9, 16, 11, 10]
Mathematica / Wolfram Language
RandomSample[Range@20]
- Output:
{14,4,2,6,20,11,17,13,16,18,15,19,12,10,1,8,3,7,5,9}
Nim
Nim standard module random
provides a PRNG based on xoroshiro128+ algorithm whose period is 2^128 − 1. It also provides the shuffle
procedure to shuffle an array or a sequence using Knuth algorithm.
Here, we have defined a procedure which accepts a slice a..b
as argument and returns a shuffled sequence of values from a to b. It uses the same algorithm as in Wren solution, i.e. a list to keep track of generated values.
import random
randomize()
proc generate(s: Slice[int]): seq[int] =
assert s.a <= s.b
var count = s.b - s.a + 1
var generated = newSeq[bool](count) # Initialized to false.
while count != 0:
let n = rand(s)
if not generated[n - s.a]:
generated[n - s.a] = true
result.add n
dec count
for i in 1..5:
echo generate(1..20)
- Output:
@[11, 15, 13, 9, 10, 6, 14, 1, 16, 4, 20, 17, 5, 7, 2, 3, 8, 12, 19, 18] @[11, 3, 15, 12, 10, 16, 6, 18, 4, 13, 14, 19, 1, 7, 2, 5, 9, 20, 17, 8] @[16, 10, 8, 1, 2, 18, 19, 4, 5, 11, 14, 15, 3, 13, 9, 12, 7, 20, 17, 6] @[4, 7, 1, 15, 11, 2, 10, 6, 19, 5, 12, 9, 14, 13, 17, 3, 18, 20, 8, 16] @[10, 9, 15, 2, 17, 8, 3, 20, 18, 12, 11, 14, 16, 13, 4, 5, 6, 1, 7, 19]
Perl
Just shuffle...
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Generate_random_numbers_without_repeating_a_value
use warnings;
use List::Util qw( shuffle );
print "@{[ shuffle 1 .. 20 ]}\n" for 1 .. 5;
- Output:
9 15 11 14 17 10 13 1 2 7 19 3 6 12 4 16 8 5 18 20 20 17 18 6 1 19 14 10 2 7 4 12 8 15 3 16 9 11 5 13 4 3 9 15 6 20 14 8 18 5 19 17 1 10 11 16 12 2 13 7 17 9 3 15 1 20 7 19 13 8 11 10 6 5 4 14 12 18 16 2 13 1 5 18 12 11 3 14 10 9 19 4 20 16 8 6 17 2 7 15
Phix
Trival use of standard builtins. Progressively filtering the output of rand(20) would gain nothing except wasted cycles. Normally I would use "with javascript_semantics", or equivalently just "with js", to explicitly specify/verify the code can be run on both the desktop and in a web browser, however here that somehow seems like overkill.
?shuffle(tagset(20))
- Output:
{13,6,8,1,9,19,5,18,2,12,11,20,4,17,10,3,15,7,14,16}
Python
import random
print(random.sample(range(1, 21), 20))
- Output:
[14, 15, 3, 18, 4, 11, 16, 10, 12, 20, 13, 1, 6, 7, 2, 17, 5, 9, 19, 8]
Quackery
As a dialogue in the Quackery shell.
Welcome to Quackery. Enter "leave" to leave the shell. /O> [] 20 times [ i^ 1+ join ] ... shuffle ... echo ... [ 7 6 9 5 13 11 15 17 19 2 14 20 12 4 8 1 3 18 10 16 ] Stack empty. /O> leave ... Auf wiedersehen.
R
R makes this so easy that it feels like you've missed the point.
sample(20)
Raku
Raku has three distinct "random" functions built in. rand() for when you want some fraction between 0 and 1. roll() when you want to select elements from a collection with replacement (rolls of a die). And pick() for when you want to select some elements from a collection without replacement. (pick a card, any card, or two cards or 10 cards...). If you want to select all the elements in random order, just pick 'whatever'. Here we'll pick all from 1 to 20, 5 times using the repetition operator.
.put for (1..20).pick(*) xx 5
- Sample output:
20 4 5 7 15 19 2 16 8 6 3 12 14 13 10 18 9 17 1 11 4 5 18 10 13 3 1 11 6 2 19 8 12 7 16 17 14 20 15 9 14 8 15 11 17 4 3 10 18 7 16 13 1 20 12 9 6 5 19 2 7 5 15 11 12 18 17 3 20 6 13 19 14 2 16 10 4 9 8 1 19 12 4 7 3 20 13 17 5 8 6 15 10 18 1 11 2 14 16 9
REXX
The REXX solution to this task is performed in essentially three parts:
: Part 1. (The DO i ...) build a list of sequential integers.
: Part 2. (The DO r ...) build an array of random integers, using the list as a selection template.
: Part 3. (The DO o ...) display a grid of the random integers with title and formatting.
With the method/algorithm used herein, there are no random numbers being discarded (due to possible
duplicates) because there cannot be any duplicates.
/*REXX program generates & displays a list of random integers (1 ──► N) with no repeats.*/
parse arg n cols seed . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 20 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /*Specified? Then use the seed. */
w= 6
title= ' random integers (1 ──► ' n") with no repeats"
say ' index │'center(title, 1 + cols*(w+1) ) /*display the output title. */
say '───────┼'center("" , 1 + cols*(w+1), '─') /* " " " separator*/
a=
do i=1 for n; a= a i /*create a list of possible integers. */
end /*i*/ /*step through the (random) integers. */
pool= n
do r=1 for n; ?= random(1, pool) /*obtain a random integer from the list*/
@.r= word(a, ?); a= delword(a, ?, 1) /*obtain random integer; del from pool.*/
pool= pool - 1 /*diminish size of the allowable pool. */
end /*r*/ /*step through the (random) integers. */
$=; idx= 1
do o=1 for n; x= @.o /*obtain a random integer from random @*/
$= $ right( x, w) /*add an integer to the output list. */
if o//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible show residual output.*/
say '───────┴'center("" , 1 + cols*(w+1), '─'); say
exit 0 /*stick a fork in it, we're all done. */
- output when using the default inputs:
index │ random integers (1 ──► 20) with no repeats ───────┼─────────────────────────────────────────────────────────────────────── 1 │ 20 7 5 12 11 6 19 8 4 10 11 │ 9 17 15 13 1 16 3 18 14 2 ───────┴───────────────────────────────────────────────────────────────────────
Ring
see "working..." + nl
decimals(3)
time1 = clock()
for num = 1 to 5
pRand()
next
time2 = clock()
time3 = time2/1000 - time1/1000
see "Elapsed time = " + time3 + " s" + nl
see "done..." + nl
func pRand
randCheck = list(20)
while true
rnd = random(19)+1
if randCheck[rnd] = 1
loop
else
randCheck[rnd] = 1
see "" + rnd + " "
ok
nr = 1
for n = 1 to len(randCheck)
if randCheck[nr] = 1
nr++
ok
next
if nr = 21
see nl
exit
ok
end
- Output:
working... 6 11 16 19 10 15 3 1 8 7 2 9 20 5 4 14 12 13 17 18 7 20 2 15 8 5 9 13 17 19 1 6 4 16 11 18 3 12 10 14 5 19 12 3 1 10 15 7 9 17 18 4 20 13 2 11 8 14 16 6 11 10 17 1 5 19 15 4 18 9 20 12 13 6 3 2 7 8 16 14 2 14 15 6 19 20 3 17 5 1 8 13 4 18 7 9 10 16 11 12 Elapsed time = 0.008 s done...
Ruby
nums = (1..20).to_a
5.times{ puts nums.shuffle.join(" ") }
- Output:
2 9 19 12 7 18 17 13 5 6 20 10 14 4 1 8 11 15 3 16 18 6 9 5 17 14 2 13 7 16 4 11 15 10 3 8 12 19 1 20 2 16 7 12 3 10 13 17 20 18 11 14 5 15 1 19 9 6 4 8 10 14 5 15 8 1 7 12 16 6 18 4 9 3 11 20 19 17 13 2 2 16 13 12 6 18 14 4 15 7 9 10 8 11 19 5 17 1 3 20
Rust
// [dependencies]
// rand = "0.7.2"
fn main() {
use rand::seq::SliceRandom;
use rand::thread_rng;
let mut rng = thread_rng();
let mut v: Vec<u32> = (1..=20).collect();
v.shuffle(&mut rng);
println!("{:?}", v);
}
- Output:
[11, 19, 1, 7, 15, 4, 13, 10, 16, 3, 2, 18, 20, 17, 9, 8, 5, 6, 12, 14]
Sidef
var nums = (1..20).to_a
5.times{ say nums.shuffle.join(" ") }
- Output:
7 16 11 2 8 5 19 1 3 17 10 4 18 6 9 13 15 20 12 14 20 4 18 7 16 2 3 10 5 13 19 17 12 1 6 11 8 15 14 9 2 6 8 18 5 15 1 13 19 17 12 3 4 7 20 16 10 11 9 14 2 18 10 16 12 14 7 13 1 8 15 20 6 17 3 11 5 9 4 19 2 17 14 15 5 13 4 16 11 18 1 10 9 7 6 12 20 3 8 19
Swift
var array = Array(1...20)
array.shuffle()
print(array)
- Output:
[4, 19, 13, 8, 14, 6, 18, 20, 11, 16, 17, 7, 5, 9, 2, 15, 3, 1, 10, 12]
Vlang
import rand
import rand.seed
fn generate(from i64, to i64) {
if to < from || from < 0 {
println("Invalid range.")
}
span := int(to - from + 1)
mut generated := []bool{len: span} // all false by default, zero indexing
mut count := span
for count > 0 {
n := from + rand.i64n(span) or {0} // upper endpoint is exclusive
if !generated[n-from] {
generated[n-from] = true
print("${n} ")
count--
}
}
println('')
}
fn main(){
rand.seed(seed.time_seed_array(2))
// generate 5 sets say
for i := 1; i <= 5; i++ {
generate(1, 20)
}
}
- Output:
Same as Go entry
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Vlang has a standard library function for this which uses the Fisher-Yates (aka Knuth) shuffle.
import rand
import rand.seed
fn main(){
rand.seed(seed.time_seed_array(2))
mut numbers := []int{len:20, init:it+1}
// generate 5 sets say
for i := 1; i <= 5; i++ {
rand.shuffle<int>(mut numbers, rand.ShuffleConfigStruct{})?
s := "${numbers:2} "
println(s[1 .. s.len-2])
}
}
- Output:
Same as go entry
Wren
This uses Wren's 'native' pseudo-random number generator which internally uses WELL512a and can generate random integers in the 32-bit range.
import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
// Generates and prints all numbers within an inclusive range whose endpoints are 32 bit integers.
// The numbers are generated in random order with any repetitions being ignored.
var generate = Fn.new { |r|
var generated = List.filled(r.to - r.from + 1, false) // zero indexing
while (generated.any { |g| !g }) {
var n = rand.int(r.from, r.to + 1) // upper endpoint is exclusive
if (!generated[n - r.from]) {
generated[n - r.from] = true
Fmt.write("$2d ", n)
}
}
System.print()
}
// generate 5 sets say
for (i in 1..5) generate.call(1..20)
- Output:
Sample run:
4 16 10 5 1 2 9 19 7 12 15 11 18 3 13 17 20 14 6 8 16 1 9 11 8 10 19 5 4 6 17 20 12 15 3 7 14 18 2 13 5 15 13 1 17 19 16 2 7 12 18 8 14 6 20 9 10 11 3 4 9 6 20 16 2 14 19 1 7 18 11 12 4 15 5 17 3 8 10 13 16 1 8 14 5 19 3 4 18 12 20 2 10 6 13 11 7 15 9 17
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Wren has a built-in function for this which uses the Fisher-Yates (aka Knuth) shuffle.
import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var numbers = (1..20).toList
for (i in 1..5) {
rand.shuffle(numbers)
Fmt.print("$2d", numbers)
}
- Output:
3 19 16 12 7 5 9 10 15 13 6 11 20 14 8 18 4 17 1 2 15 1 18 14 4 20 11 2 6 3 12 5 7 10 16 17 9 13 19 8 19 6 14 1 13 2 18 20 11 8 5 3 9 12 15 17 4 16 10 7 16 15 5 10 1 13 17 6 8 9 20 3 14 11 18 2 19 12 4 7 17 6 10 13 20 5 3 11 18 12 16 2 14 15 19 9 8 1 4 7
XPL0
int Set, R;
[Set:= 0;
repeat R:= Ran(20);
if (Set & 1<<R) = 0 then
[Set:= Set ! 1<<R;
IntOut(0, R+1); ChOut(0, ^ )];
until Set = $F_FFFF;
]
- Output:
Example outputs:
14 5 1 20 18 16 2 3 19 6 4 13 7 11 17 10 8 12 15 9 18 19 8 11 9 6 5 4 12 2 3 1 16 15 14 7 20 13 10 17 5 11 17 19 2 14 20 18 9 16 1 15 4 8 12 10 13 6 7 3 17 11 13 20 3 7 8 9 19 5 4 18 15 14 16 12 1 2 6 10