Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random numbers without collisions

Tags:

bash

random

I want to generate different random numbers in bash . I used $RANDOM , but in my output some numbers are identical.

var1=$((1+$RANDOM%48))
var2=$((1+$RANDOM%48))
var3=$((1+$RANDOM%48))
var4=$((1+$RANDOM%48))
var5=$((1+$RANDOM%48))
var6=$((1+$RANDOM%48))

it gives me 6 numbers between 1 and 48 but i need 6 DIFFERENT numbers between 1 and 48, the fact is that im really new and i dont know even how to start.

like image 387
Nicolas Ortiguera Avatar asked Oct 26 '17 00:10

Nicolas Ortiguera


People also ask

Is there a real random number generator?

True Random Number GeneratorsA true random number generator — a hardware random number generator (HRNG) or true random number generator (TRNG) — is cryptographically secure and takes into account physical attributes such as atmospheric or thermal conditions. Such tools may also take into account measurement biases.


2 Answers

if you want 6 different pseudo-random numbers between 1-48 this is one way to make it

$ seq 48 | shuf | head -6


18
10
17
3
11
6

or directly with shuf options (as in this answer)

shuf -i 1-48 -n 6

another method would be rejection sampling. With awk

awk 'BEGIN{srand(); 
           do {a[int(1+rand()*48)]} while (length(a)<6); 
           for(k in a) print k}'

8
14
16
23
24
27

here rejection is implicit, adding the same number again won't increase the array size (essentially a hash map)

to assign result to variable is possible, but the structure begs for array use, for example

declare -a randarray
readarray randarray < <(seq 48 | shuf | head -6)

you can access the individual elements with the corresponding index (0-based)

echo ${randarray[3]}

In general if your number of samples are close to the range of the sample space, you will want shuffle (extreme case if you want N numbers from the range 1-N, what you're asking is a random permutation), or if the ratio is small, rejection sampling might be better, (extreme case you want one random variable). Rejection sampling is used mostly if you have other conditions to eliminate a sample. However, direct use of shuf with options is very fast already and you may not need rejection sampling method at all for basic uses.

like image 188
karakfa Avatar answered Sep 28 '22 10:09

karakfa


shuf -i 1-48 -n 6

will give you 6 random numbers between 1 and 48. All will be different per default.

like image 44
Cloth Tiger Avatar answered Sep 28 '22 10:09

Cloth Tiger