Generate random numbers without collisions

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))

he gives me 6 numbers from 1 to 48, but I need 6 DIFFERENT numbers from 1 to 48, the fact is that they are really new, and I don’t even know how to start.

+6
source share
3 answers

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

$ seq 48 | shuf | head -6


18
10
17
3
11
6

or directly with parameters shuf(as in this answer )

shuf -i 1-48 -n 6

another method would be sampling the rejects. Throughawk

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 the deviation is implicit, adding the number again will not increase the size of the array (essentially a hash map)

, , ,

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

( 0)

echo ${randarray[3]}

, , ( , , N 1-N, , , ), , ( ). , . , shuf .

+7

shuf -i 1-48 -n 6

6 1 48. - .

+3

This algorithm will pump six random numbers and check each of them to make sure there are no duplicates.

declare -a nums

let times=6

for i in $(eval echo {0..$times}); do
    let nums[$i]=0
    let dup=1
    while [ $dup -eq 1 ]; do
        let temp=$((1+$RANDOM%48))
        let dup=0

        for j in $(eval echo {0..${#nums[*]}}); do
            let cur=$((${nums[$j]}))
            if ! [ "$cur" -eq "$cur" ] 2> /dev/null; then
                break
            fi
            if [ "$cur" -eq "$(eval echo $temp)" ]; then
                let dup=1
            fi
        done
    done

    let nums[$(($j - 1))]=$temp
done

echo ${nums[@]:0}

exit 1
0
source

All Articles