Generate random numbers without repeating a value: Difference between revisions
Generate random numbers without repeating a value (view source)
Revision as of 14:06, 27 August 2022
, 1 year agosyntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 22:
{{trans|Nim}}
<
[Int] result
V count = b - a + 1
Line 36:
L 5
print(generate(1, 20))</
{{out}}
Line 48:
=={{header|Action!}}==
<
BYTE i
Line 86:
PrintTable(tab,LEN)
OD
RETURN</
{{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]
Line 105:
{{libheader|ALGOL 68-rows}}
This is vertually identical to the Algol 68 sample for the Knuth Shuffle Task.
<
# same as the Knuth Shuffle sample, but with different display #
Line 129:
knuth shuffle(a);
SHOW a
)</
{{out}}
<pre>
Line 136:
=={{header|AppleScript}}==
<
-- 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'.
Line 175:
end task
task()</
{{output}}
<
=={{header|Arturo}}==
<
result: new []
Line 195:
loop 3 'x [
print generateUniqueRandoms
]</
{{out}}
Line 204:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f GENERATE_RANDOM_NUMBERS_WITHOUT_REPEATING_A_VALUE.AWK
BEGIN {
Line 221:
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 230:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<
for num = 1 to 5
call pRand()
Line 252:
until nr = 21
print
end subroutine</
==={{header|QBasic}}===
{{trans|FreeBASIC}}
<
RANDOMIZE TIMER
Line 279:
LOOP UNTIL nr = 21
PRINT
END SUB</
=={{header|F_Sharp|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 ""
</syntaxhighlight>
{{out}}
<pre>
Line 294:
Generating a random permutation of 1..20:
{{works with|Factor|0.99 2021-06-02}}
<
sequences ;
Line 300:
[ length dup nPk random ] keep permutation ;
20 [1,b] random-permutation .</
{{out}}
<pre>
Line 307:
Shuffling 1..20:
{{works with|Factor|0.99 2021-06-02}}
<
20 [1,b] >vector randomize .</
{{out}}
<pre>
Line 316:
Sampling 20 elements from 1..20:
{{works with|Factor|0.99 2021-06-02}}
<
20 [1,b] 20 sample .</
{{out}}
<pre>
Line 326:
=={{header|FreeBASIC}}==
<
Dim As Integer randCheck(20), nr = 1
Do
Line 347:
pRand()
Next num
Sleep</
{{out}}
<pre>
Line 361:
{{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.
<
import (
Line 398:
generate(1, 20)
}
}</
{{out}}
Line 411:
<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.
<
import (
Line 432:
fmt.Println(s[1 : len(s)-2])
}
}</
{{out}}
Line 444:
=={{header|Haskell}}==
<
import Data.Ord (comparing)
import System.Random (newStdGen, randomRs)
Line 459:
main =
inRandomOrder [1 .. 20]
>>= print</
{{Out}}
For example:
Line 465:
=={{header|Java}}==
<
public class RandomShuffle {
Line 476:
System.out.println(list);
}
}</
{{out}}
Line 485:
=={{header|JavaScript}}==
<
"use strict";
Line 540:
// MAIN ---
return JSON.stringify(main());
})();</
{{Out}}
For example:
Line 551:
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:
<
In the following, a bash or bash-like scripting environment is assumed, and the jq command is assumed to be "jq".
<syntaxhighlight lang="sh">
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq
</syntaxhighlight>
'''program.jq'''
<
def prn:
if . == 1 then 0
Line 581:
# The task:
[range(1;21)] | knuthShuffle</
{{out}}
<pre>
Line 608:
=={{header|Julia}}==
Julia's Random module contains a function called `randperm(n::Integer)` which constructs a random permutation of integers from 1 to n.
<
@show randperm(20)
</
<pre>
randperm(20) = [20, 2, 5, 6, 18, 14, 12,4, 13, 7, 15, 3, 19, 17, 1, 9, 16, 11, 10]
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang
{{out}}<pre>
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.
<
randomize()
Line 643:
for i in 1..5:
echo generate(1..20)</
{{out}}
Line 654:
=={{header|Perl}}==
Just shuffle...
<
use strict; # https://rosettacode.org/wiki/Generate_random_numbers_without_repeating_a_value
Line 660:
use List::Util qw( shuffle );
print "@{[ shuffle 1 .. 20 ]}\n" for 1 .. 5;</
{{out}}
<pre>
Line 673:
=={{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.
<!--<
<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>
<!--</
{{out}}
<pre>
Line 682:
=={{header|Python}}==
<
import random
print(random.sample(range(1, 21), 20))
</
=={{header|Quackery}}==
Line 711:
=={{header|R}}==
R makes this so easy that it feels like you've missed the point.
<syntaxhighlight lang
=={{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.
<syntaxhighlight lang="raku"
{{out|Sample output}}
<pre>20 4 5 7 15 19 2 16 8 6 3 12 14 13 10 18 9 17 1 11
Line 732:
With the method/algorithm used herein, there are no random numbers being discarded (due to possible
<br>duplicates) because there cannot ''be'' any duplicates.
<
parse arg n cols seed . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 20 /*Not specified? Then use the default.*/
Line 759:
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. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 769:
</pre>
=={{header|Ring}}==
<
see "working..." + nl
decimals(3)
Line 803:
ok
end
</syntaxhighlight>
{{out}}
<pre>
Line 817:
=={{header|Ruby}}==
<
5.times{ puts nums.shuffle.join(" ") }</
{{out}}
<pre>2 9 19 12 7 18 17 13 5 6 20 10 14 4 1 8 11 15 3 16
Line 827:
</pre>
=={{header|Rust}}==
<
// rand = "0.7.2"
Line 837:
v.shuffle(&mut rng);
println!("{:?}", v);
}</
{{out}}
Line 846:
=={{header|Sidef}}==
{{trans|Ruby}}
<
5.times{ say nums.shuffle.join(" ") }</
{{out}}
Line 859:
=={{header|Swift}}==
<
array.shuffle()
print(array)</
{{out}}
Line 870:
=={{header|Vlang}}==
{{trans|go}}
<
import rand.seed
Line 897:
generate(1, 20)
}
}</
{{out}}
<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.
<
import rand.seed
Line 914:
println(s[1 .. s.len-2])
}
}</
{{out}}
Line 924:
{{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.
<
import "/fmt" for Fmt
Line 944:
// generate 5 sets say
for (i in 1..5) generate.call(1..20)</
{{out}}
Line 957:
<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.
<
import "/fmt" for Fmt
Line 965:
rand.shuffle(numbers)
Fmt.print("$2d", numbers)
}</
{{out}}
Line 977:
=={{header|XPL0}}==
<
[Set:= 0;
repeat R:= Ran(20);
Line 984:
IntOut(0, R+1); ChOut(0, ^ )];
until Set = $F_FFFF;
]</
{{out}}
|