I need to generate random unique numbers within a certain range, how should I do it? I can generate random numbers by
generator: $arr = []; $x = rand($min, $max); $len = count($arr); $flag = 0; for($i = 0; $i < $len; $i++) { if ($flag === 1) goto generator; if ($x === $arr[$i]) $flag = 1; } $arr[$index] = $x; $index++; goto generator;
I know this code is bad, so I need to make my version better optimized code! help!
Example: If I need to generate 3 numbers between 1 and 15, they should be like 5, 9, 1, but not 3, 1, 2 [in 1 - 3 (the numbers I want to generate)]
I'd be interested to know how the accepted answer differs from my answer. It's worth noting that a mix of the two can be advantageous; in fact, here's a function that conditionally uses one or the other based on some value:
result:
The accepted answer is definitely optimal if you use a smaller range and a higher number of return values; however, as I expected, a larger range and smaller count will take longer Time to accept the answer since it has to store every possible value in the range. You even run the risk of exceeding PHP's memory limit. Evaluating the ratio between range and count and conditionally choosing a hybrid of generators would be the best of both worlds.
Array with ranges of numbers in random order:
Packaging function:
Example:
result: