Generate random numbers without repeating a value: Difference between revisions

Added Easylang
(Added XPL0 example.)
(Added Easylang)
 
(29 intermediate revisions by 16 users not shown)
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 100:
14 2 1 18 10 7 13 11 17 4 20 9 6 3 16 19 5 15 12 8
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
-- Generate the integers 1 .. 20 in random order
-- J. Carter 2023 Apr
 
with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
 
procedure Random_20 is
subtype Desired_Value is Integer range 1 .. 20;
package Desired_Random is new Ada.Numerics.Discrete_Random (Result_Subtype => Desired_Value);
type Desired_List is array (Desired_Value) of Desired_Value;
List : Desired_List;
Gen : Desired_Random.Generator;
Idx : Desired_Value;
begin -- Random_20
Fill : for I in List'Range loop
List (I) := I;
end loop Fill;
 
Desired_Random.Reset (Gen => Gen);
Randomize : for I in List'Range loop
Idx := Desired_Random.Random (Gen);
Swap : declare
Temp : Desired_Value := List (Idx);
begin -- Swap
List (Idx) := List (I);
List (I) := Temp;
end Swap;
end loop Randomize;
Print : for V of List loop
Ada.Text_IO.Put (Item => V'Image);
end loop Print;
Ada.Text_IO.New_Line;
end Random_20;
</syntaxhighlight>
{{out}}
<pre>
8 3 18 12 2 20 17 11 5 13 9 15 6 14 19 4 16 1 10 7
17 1 7 10 8 9 6 11 19 20 2 15 13 14 12 4 16 18 3 5
</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{libheader|ALGOL 68-rows}}
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 #
 
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
)</syntaxhighlight>
{{out}}
<pre>
17 6 11 5 7 15 18 8 4 3 10 13 9 2 12 1 19 14 20 16
</pre>
 
=={{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.
-- 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()</syntaxhighlight>
 
{{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}}==
 
<syntaxhighlight lang="rebol">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
]</syntaxhighlight>
 
{{out}}
 
<pre>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</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GENERATE_RANDOM_NUMBERS_WITHOUT_REPEATING_A_VALUE.AWK
BEGIN {
Line 119 ⟶ 270:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 128 ⟶ 279:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight BASIC256lang="basic256">arraybase 1
for num = 1 to 5
call pRand()
Line 150 ⟶ 301:
until nr = 21
print
end subroutine</langsyntaxhighlight>
 
==={{header|QBasic}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="qbasic">DECLARE SUB pRand ()
 
RANDOMIZE TIMER
Line 177 ⟶ 328:
LOOP UNTIL nr = 21
PRINT
END SUB</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
Creates a "TRandomizer" object which makes it easy to setup and use multiple non repeating randomizers. Since the objects are independent, each one can have different parameters.
 
<syntaxhighlight lang="Delphi">
 
{Create randomize object to make it easier to use}
 
type TRandomizer = class(TObject)
private
FSize: integer;
procedure SetSize(const Value: integer);
protected
procedure Randomize;
public
Numbers: array of Integer;
constructor Create;
property Size: integer read FSize write SetSize;
end;
 
{ TRandomizer }
 
constructor TRandomizer.Create;
begin
Size:=20;
end;
 
procedure TRandomizer.Randomize;
var I,Inx1,Inx2,T: integer;
begin
for I:=1 to 100 do
begin
Inx1:=Random(Length(Numbers));
Inx2:=Random(Length(Numbers));
T:=Numbers[Inx1];
Numbers[Inx1]:=Numbers[Inx2];
Numbers[Inx2]:=T;
end;
 
end;
 
procedure TRandomizer.SetSize(const Value: integer);
var I: integer;
begin
if FSize<>Value then
begin
FSize:=Value;
SetLength(Numbers,FSize);
for I:=0 to FSize-1 do Numbers[I]:=I+1;
Randomize;
end;
end;
 
{------------------------------------------------------------------------------}
 
procedure ShowRandomNumbers(Memo: TMemo);
var RD: TRandomizer;
var S: string;
var I,J: integer;
begin
RD:=TRandomizer.Create;
try
RD.Size:=20;
for J:=1 to 5 do
begin
RD.Randomize;
S:='[';
for I:=0 to High(RD.Numbers) do
S:=S+Format('%3D',[RD.Numbers[I]]);
S:=S+']';
Memo.Lines.Add(S);
end;
finally RD.Free; end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
[ 20 12 9 19 2 8 16 14 10 4 11 6 18 5 7 1 17 3 15 13]
[ 7 12 20 13 4 19 8 3 17 5 2 6 9 1 15 11 18 16 10 14]
[ 19 12 7 20 6 16 1 10 13 15 4 2 8 9 3 17 11 18 14 5]
[ 18 13 12 20 8 2 3 10 4 16 19 1 7 5 11 15 9 6 17 14]
[ 17 20 19 3 6 10 12 9 5 16 18 7 8 13 4 15 1 11 14 2]
</pre>
 
 
=={{header|EasyLang}}==
<syntaxhighlight>
proc shuffle . a[] .
for i = len a[] downto 2
r = randint i
swap a[r] a[i]
.
.
for i to 20
arr[] &= i
.
shuffle arr[]
print arr[]
</syntaxhighlight>
{{out}}
<pre>
[ 18 12 19 10 11 4 2 3 6 20 8 16 15 9 7 17 1 14 5 13 ]
</pre>
 
=={{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 192 ⟶ 450:
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 198 ⟶ 456:
[ length dup nPk random ] keep permutation ;
 
20 [1,b] random-permutation .</langsyntaxhighlight>
{{out}}
<pre>
Line 205 ⟶ 463:
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 214 ⟶ 472:
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 224 ⟶ 482:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Sub pRand
Dim As Integer randCheck(20), nr = 1
Do
Line 245 ⟶ 503:
pRand()
Next num
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 259 ⟶ 517:
{{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 296 ⟶ 554:
generate(1, 20)
}
}</langsyntaxhighlight>
 
{{out}}
Line 309 ⟶ 567:
<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 330 ⟶ 588:
fmt.Println(s[1 : len(s)-2])
}
}</langsyntaxhighlight>
 
{{out}}
Line 340 ⟶ 598:
13 12 8 3 9 17 14 10 6 2 11 20 19 18 4 7 16 1 15 5
</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{Out}}
For example:
<pre>[16,1,3,9,8,20,12,18,11,19,2,14,5,6,13,15,17,10,7,4]</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j">>: ?~ 20</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang ="java">import java.util.*;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;
</syntaxhighlight>
<syntaxhighlight lang="java">
int[] randomList() {
/* 'Set' allows only unique values */
/* 'LinkedHashSet' will preserve the input order */
Set<Integer> set = new LinkedHashSet<>();
Random random = new Random();
while (set.size() < 20)
set.add(random.nextInt(1, 21));
int[] values = new int[set.size()];
/* 'Set' does not have a 'get' method */
Iterator<Integer> iterator = set.iterator();
int index = 0;
while (iterator.hasNext())
values[index++] = iterator.next();
return values;
}
</syntaxhighlight>
<pre>
8, 3, 2, 17, 11, 4, 6, 15, 20, 9, 14, 10, 5, 19, 18, 7, 12, 13, 1, 16
</pre>
<pre>
6, 7, 20, 14, 1, 2, 10, 5, 13, 8, 4, 12, 16, 15, 17, 11, 18, 3, 19, 9
</pre>
<br />
<syntaxhighlight lang="java">import java.util.*;
 
public class RandomShuffle {
Line 353 ⟶ 665:
System.out.println(list);
}
}</langsyntaxhighlight>
 
{{out}}
Line 359 ⟶ 671:
[19, 15, 10, 6, 17, 13, 14, 9, 2, 20, 3, 18, 8, 16, 7, 12, 1, 4, 5, 11]
</pre>
 
=={{header|JavaScript}}==
<syntaxhighlight lang="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());
})();</syntaxhighlight>
{{Out}}
For example:
<pre>[6,9,8,16,5,15,19,7,13,12,4,20,1,2,18,11,14,17,10,3]</pre>
 
=={{header|jq}}==
Line 366 ⟶ 739:
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 396 ⟶ 769:
 
# The task:
[range(1;21)] | knuthShuffle</langsyntaxhighlight>
{{out}}
<pre>
Line 422 ⟶ 795:
 
=={{header|Julia}}==
Julia's Random module contains a function called `randpermshuffle(n[rng=GLOBAL_RNG,] v::IntegerAbstractArray)` which constructs a randomrandomly permutationpermuted copy of integers from 1 to nv.
<langsyntaxhighlight lang="julia">using Random
Random.seed!(1234567)
@show randperm(20)
 
</lang>{{out}}
# 1. built in
 
@show shuffle(1:20)
 
# 2. from standard random generator rand()
 
myshuffle(urn::AbstractVector) =
map(length(urn):-1:1) do len
ball = urn[ceil(Int, rand() * len)]
urn = setdiff(urn, ball)
ball
end
 
@show myshuffle(1:20);</syntaxhighlight>{{out}}
<pre>
randpermshuffle(1:20) = [204, 217, 515, 614, 1811, 145, 12,418, 136, 7, 158, 316, 193, 1720, 113, 912, 1619, 112, 10, 1, 9]
myshuffle(1:20) = [5, 10, 19, 3, 15, 13, 18, 1, 6, 8, 2, 11, 4, 20, 17, 14, 9, 16, 7, 12]
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang Mathematica="mathematica">RandomSample[Range@20]</langsyntaxhighlight>
 
{{out}}<pre>
Line 442 ⟶ 831:
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 458 ⟶ 847:
 
for i in 1..5:
echo generate(1..20)</langsyntaxhighlight>
 
{{out}}
Line 469 ⟶ 858:
=={{header|Perl}}==
Just shuffle...
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Generate_random_numbers_without_repeating_a_value
Line 475 ⟶ 864:
use List::Util qw( shuffle );
 
print "@{[ shuffle 1 .. 20 ]}\n" for 1 .. 5;</langsyntaxhighlight>
{{out}}
<pre>
Line 488 ⟶ 877:
=={{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 497 ⟶ 886:
 
=={{header|Python}}==
===Version 1===
<lang python>
<syntaxhighlight lang="python">
import random
 
print(random.sample(range(1, 21), 20))
</syntaxhighlight>
</lang>{{out}}[14, 15, 3, 18, 4, 11, 16, 10, 12, 20, 13, 1, 6, 7, 2, 17, 5, 9, 19, 8]
{{out}}
<pre>
[14, 15, 3, 18, 4, 11, 16, 10, 12, 20, 13, 1, 6, 7, 2, 17, 5, 9, 19, 8]
</pre>
 
===Version 2===
<syntaxhighlight lang="python">
import random as r
 
def GenerateRandomSet(n: int) -> list:
set_ = list(range(1, n+1))
r.shuffle(set_)
return set_
</syntaxhighlight>
 
=={{header|Quackery}}==
Line 526 ⟶ 930:
=={{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.
 
Pick random elements ''without'' replacement
<lang perl6>.put for (1..20).pick(*) xx 5</lang>
<syntaxhighlight lang="raku" line>.put for (1..20).pick(*) xx 5</syntaxhighlight>
{{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 538 ⟶ 943:
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</pre>
 
Pick random elements ''with'' replacement
<syntaxhighlight lang="raku" line>.put for (1..20).roll(20) xx 5</syntaxhighlight>
{{out|Sample output}}
<pre>16 20 15 17 13 4 19 1 3 8 4 12 13 4 4 5 14 17 10 14
12 6 8 8 9 6 2 4 16 8 4 3 14 8 19 20 5 12 7 15
20 4 20 16 14 6 15 15 16 18 5 19 20 3 14 11 2 7 13 12
3 19 11 13 9 4 5 11 2 20 16 17 14 18 12 10 4 1 13 2
17 20 12 17 19 4 20 20 14 8 2 19 2 12 18 14 4 14 10 8</pre>
 
=={{header|REXX}}==
Line 547 ⟶ 961:
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 574 ⟶ 988:
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 584 ⟶ 998:
</pre>
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "working..." + nl
decimals(3)
Line 618 ⟶ 1,032:
ok
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 629 ⟶ 1,043:
Elapsed time = 0.008 s
done...
</pre>
 
=={{header|RPL}}==
'''Stand-alone implementation'''
≪ 0 → n r
≪ 1 n '''FOR''' j j '''NEXT''' <span style="color:grey">@ fill stack with 1, 2,..n</span>
1 n '''START'''
n 1 - RAND * CEIL 1 + 'r' STO
r ROLL SWAP r ROLLD <span style="color:grey">@ swap 2 stack levels randomly, n times</span>
n ROLL
'''NEXT'''
n →LIST
≫ ≫ '<span style="color:blue">SHUFFLE</span>' STO
'''Using Knuth shuffle'''
 
<code>KNUTH</code> is defined at [[Knuth shuffle#RPL|Knuth shuffle]]
≪ { }
1 ROT '''FOR''' j j + '''NEXT'''
<span style="color:blue">KNUTH </span>
≫ '<span style="color:blue">SHUFFLE</span>' STO
 
20 <span style="color:blue">SHUFFLE</span>
{{out}}
<pre>
1: { 3 13 14 1 7 10 4 9 12 11 16 15 18 17 20 6 19 8 2 5 }
</pre>
 
=={{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 641 ⟶ 1,080:
2 16 13 12 6 18 14 4 15 7 9 10 8 11 19 5 17 1 3 20
</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">// [dependencies]
// rand = "0.7.2"
 
Line 652 ⟶ 1,092:
v.shuffle(&mut rng);
println!("{:?}", v);
}</langsyntaxhighlight>
 
{{out}}
<pre>
[11, 19, 1, 7, 15, 4, 13, 10, 16, 3, 2, 18, 20, 17, 9, 8, 5, 6, 12, 14]
</pre>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">var nums = (1..20).to_a
5.times{ say nums.shuffle.join(" ") }</syntaxhighlight>
 
{{out}}
<pre>
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
</pre>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">var array = Array(1...20)
array.shuffle()
print(array)</langsyntaxhighlight>
 
{{out}}
<pre>
[4, 19, 13, 8, 14, 6, 18, 20, 11, 16, 17, 7, 5, 9, 2, 15, 3, 1, 10, 12]
</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (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)
}
}</syntaxhighlight>
{{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.
<syntaxhighlight lang="vlang">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])
}
}</syntaxhighlight>
 
{{out}}
<pre>
Same as go entry
</pre>
 
Line 672 ⟶ 1,179:
{{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 ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
 
var rand = Random.new()
Line 692 ⟶ 1,199:
 
// generate 5 sets say
for (i in 1..5) generate.call(1..20)</langsyntaxhighlight>
 
{{out}}
Line 705 ⟶ 1,212:
<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 ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
 
var rand = Random.new()
Line 713 ⟶ 1,220:
rand.shuffle(numbers)
Fmt.print("$2d", numbers)
}</langsyntaxhighlight>
 
{{out}}
Line 725 ⟶ 1,232:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">int Set, R;
[Set:= 0;
repeat R:= Ran(20);
Line 732 ⟶ 1,239:
IntOut(0, R+1); ChOut(0, ^ )];
until Set = $F_FFFF;
]</langsyntaxhighlight>
 
{{out}}
1,978

edits