Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to generate N unique random numbers between min and max in PHP

2 Answers

0 votes
function generateUniqueRandomNumbers($N, $min, $max) {
    $uniqueNumbers = [];

    if ($N > ($max - $min + 1)) {
        echo "Not enough unique numbers in the given range.";
        return;
    }

    while (count($uniqueNumbers) < $N) {
        $randomNumber = rand($min, $max);
        if (!in_array($randomNumber, $uniqueNumbers)) {
            $uniqueNumbers[] = $randomNumber;
        }
    }

    return $uniqueNumbers;
}

$N = 8;
$uniqueRandomNumbers = generateUniqueRandomNumbers($N, 1, 20);

print_r($uniqueRandomNumbers);


/*
run:

Array
(
    [0] => 16
    [1] => 14
    [2] => 17
    [3] => 3
    [4] => 20
    [5] => 5
    [6] => 4
    [7] => 1
)

*/

 



answered Sep 25, 2024 by avibootz
0 votes
function generateUniqueRandomNumbers($N, $min, $max) {
    $uniqueNumbers = [];

    while (count($uniqueNumbers) < $N) {
        $num = rand($min, $max);
        $uniqueNumbers[$num] = true; // Use the number as a key to ensure uniqueness
    }

    return array_keys($uniqueNumbers);
}

$N = 8; // Number of unique random numbers

$randomNumbers = generateUniqueRandomNumbers($N, 1, 20);

foreach ($randomNumbers as $num) {
    echo $num . " ";
}



/*
run:
 
9 7 4 3 15 16 20 17 
 
*/

 



answered Sep 25, 2024 by avibootz

Related questions

...