Jump to content

Generate random numbers without repeating a value: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 22:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F generate(a, b)
[Int] result
V count = b - a + 1
Line 36:
 
L 5
print(generate(1, 20))</langsyntaxhighlight>
 
{{out}}
Line 48:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintTable(BYTE ARRAY tab BYTE size)
BYTE i
 
Line 86:
PrintTable(tab,LEN)
OD
RETURN</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="algol68"># generate a set of 20 random integers without duplicates #
# same as the Knuth Shuffle sample, but with different display #
 
Line 129:
knuth shuffle(a);
SHOW a
)</langsyntaxhighlight>
{{out}}
<pre>
Line 136:
 
=={{header|AppleScript}}==
<langsyntaxhighlight 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.
-- Calls to the handler after all the numbers have been used just return 'missing value'.
Line 175:
end task
 
task()</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{16, 9, 12, 6, 17, 10, 1, 5, 3, 2, 7, 20, 14, 18, 19, 11, 15, 13, 8, 4}</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">generateUniqueRandoms: function [][
result: new []
 
Line 195:
loop 3 'x [
print generateUniqueRandoms
]</langsyntaxhighlight>
 
{{out}}
Line 204:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GENERATE_RANDOM_NUMBERS_WITHOUT_REPEATING_A_VALUE.AWK
BEGIN {
Line 221:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 230:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight BASIC256lang="basic256">arraybase 1
for num = 1 to 5
call pRand()
Line 252:
until nr = 21
print
end subroutine</langsyntaxhighlight>
 
==={{header|QBasic}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="qbasic">DECLARE SUB pRand ()
 
RANDOMIZE TIMER
Line 279:
LOOP UNTIL nr = 21
PRINT
END SUB</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// 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>
</lang>
{{out}}
<pre>
Line 294:
Generating a random permutation of 1..20:
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: kernel math.combinatorics math.ranges prettyprint random
sequences ;
 
Line 300:
[ length dup nPk random ] keep permutation ;
 
20 [1,b] random-permutation .</langsyntaxhighlight>
{{out}}
<pre>
Line 307:
Shuffling 1..20:
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: math.ranges prettyprint random vectors ;
 
20 [1,b] >vector randomize .</langsyntaxhighlight>
{{out}}
<pre>
Line 316:
Sampling 20 elements from 1..20:
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: math.ranges prettyprint random ;
 
20 [1,b] 20 sample .</langsyntaxhighlight>
{{out}}
<pre>
Line 326:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Sub pRand
Dim As Integer randCheck(20), nr = 1
Do
Line 347:
pRand()
Next num
Sleep</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 398:
generate(1, 20)
}
}</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 432:
fmt.Println(s[1 : len(s)-2])
}
}</langsyntaxhighlight>
 
{{out}}
Line 444:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (sortBy)
import Data.Ord (comparing)
import System.Random (newStdGen, randomRs)
Line 459:
main =
inRandomOrder [1 .. 20]
>>= print</langsyntaxhighlight>
{{Out}}
For example:
Line 465:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.*;
 
public class RandomShuffle {
Line 476:
System.out.println(list);
}
}</langsyntaxhighlight>
 
{{out}}
Line 485:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 540:
// MAIN ---
return JSON.stringify(main());
})();</langsyntaxhighlight>
{{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:
<langsyntaxhighlight lang="jq">[range(1;21)] | knuthShuffle</langsyntaxhighlight>
 
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
</syntaxhighlight>
</lang>
'''program.jq'''
<langsyntaxhighlight lang="jq"># Output: a prn in range(0;$n) where $n is `.`
def prn:
if . == 1 then 0
Line 581:
 
# The task:
[range(1;21)] | knuthShuffle</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="julia">using Random
@show randperm(20)
</langsyntaxhighlight>{{out}}
<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 Mathematica="mathematica">RandomSample[Range@20]</langsyntaxhighlight>
 
{{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.
 
<langsyntaxhighlight Nimlang="nim">import random
 
randomize()
Line 643:
 
for i in 1..5:
echo generate(1..20)</langsyntaxhighlight>
 
{{out}}
Line 654:
=={{header|Perl}}==
Just shuffle...
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
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;</langsyntaxhighlight>
{{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.
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 682:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
import random
 
print(random.sample(range(1, 21), 20))
</langsyntaxhighlight>{{out}}[14, 15, 3, 18, 4, 11, 16, 10, 12, 20, 13, 1, 6, 7, 2, 17, 5, 9, 19, 8]
 
=={{header|Quackery}}==
Line 711:
=={{header|R}}==
R makes this so easy that it feels like you've missed the point.
<syntaxhighlight lang ="rsplus">sample(20)</langsyntaxhighlight>
 
=={{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" perl6line>.put for (1..20).pick(*) xx 5</langsyntaxhighlight>
{{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, &nbsp; there are &nbsp; no &nbsp; random numbers being discarded &nbsp; (due to possible
<br>duplicates) &nbsp; because there cannot &nbsp; ''be'' &nbsp; any duplicates.
<langsyntaxhighlight 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.*/
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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 769:
</pre>
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "working..." + nl
decimals(3)
Line 803:
ok
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 817:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">nums = (1..20).to_a
5.times{ puts nums.shuffle.join(" ") }</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="rust">// [dependencies]
// rand = "0.7.2"
 
Line 837:
v.shuffle(&mut rng);
println!("{:?}", v);
}</langsyntaxhighlight>
 
{{out}}
Line 846:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">var nums = (1..20).to_a
5.times{ say nums.shuffle.join(" ") }</langsyntaxhighlight>
 
{{out}}
Line 859:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">var array = Array(1...20)
array.shuffle()
print(array)</langsyntaxhighlight>
 
{{out}}
Line 870:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="vlang">import rand
import rand.seed
 
Line 897:
generate(1, 20)
}
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="vlang">import rand
import rand.seed
 
Line 914:
println(s[1 .. s.len-2])
}
}</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
 
Line 944:
 
// generate 5 sets say
for (i in 1..5) generate.call(1..20)</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
 
Line 965:
rand.shuffle(numbers)
Fmt.print("$2d", numbers)
}</langsyntaxhighlight>
 
{{out}}
Line 977:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">int Set, R;
[Set:= 0;
repeat R:= Ran(20);
Line 984:
IntOut(0, R+1); ChOut(0, ^ )];
until Set = $F_FFFF;
]</langsyntaxhighlight>
 
{{out}}
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.