0

I wrote a code which is generating 3 random unique numbers from the range. It seems working, but I want to know is it working correctly and is my code suitable for a bigger range. For example, if I want to generate not 3, but 300 random unique numbers from a 1 to 10^6 range. How my code will perform in terms of memory usage and execution time?

The code is working, but I'm not sure about it. Just want to be sure, that I'm not missing something.

<?php
    $array=range(1,100);
    $rand = array_rand($array,3);
    echo "Random number 1: ".$array[$rand[0]]."\n";
    echo "Random number 2: ".$array[$rand[1]]."\n";
    echo "Random number 3: ".$array[$rand[2]]."\n";
?>

As a result I want working code which is good in terms of performance.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Aleksey
  • 13
  • 2
  • 2
    I think this question would be better suited at https://codereview.stackexchange.com/ – LLJ97 Jul 09 '19 at 08:05
  • See this [answer](https://stackoverflow.com/a/5612704/6556397) too – Rahul Jul 09 '19 at 08:06
  • 1
    I would suggest trying it out and looking at the results. – Jerodev Jul 09 '19 at 08:07
  • 1
    Definitely NOT suitable for a range to 10^6 as you would have to create a hugh array that would at best waste memory or at worst expand beyond its limits – RiggsFolly Jul 09 '19 at 08:07
  • Another possibility would be to use a for loop and the `rand()` method. Tested it and worked pretty fast for 300 numbers with a range of 1 to 1000000. – LLJ97 Jul 09 '19 at 08:12
  • 1
    The [second rated answer](https://stackoverflow.com/a/5612725/7393478) from the question cited by @ÐℛẲḰỮℒѦ answers quite well your question about performance (for higher range, it's better) – Kaddath Jul 09 '19 at 08:14
  • 1
    Thank you for your answers! Answer by ÐℛẲḰỮℒѦ is suitable for me. – Aleksey Jul 10 '19 at 03:23

1 Answers1

0

Recursive function will help in this case

$r = f(1,1000000,300);

print_r($r);

function f($min, $max, $total, $current=[]){
  if(count($current) == $total){
    return $current;
  }
  $n = rand($min,$max);
  in_array($n, $current) ? '' : ($current[] = $n);
  return f($min, $max, $total, $current);
}

enter image description here

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20