I need to generate random UNIQUE numbers within a range, how can I do that? I can generate random number 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 a better optimized code of my version ! help !
example: if i need to generate 3 numbers within 1 to 15 they should be like 5, 9, 1 but not 3,1,2 [with in 1 - 3 (numbers i want to generate) ]
Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.
Array with range of numbers at random order:
$numbers = range(1, 20); shuffle($numbers);
Wrapped function:
function UniqueRandomNumbersWithinRange($min, $max, $quantity) { $numbers = range($min, $max); shuffle($numbers); return array_slice($numbers, 0, $quantity); }
Example:
<?php print_r( UniqueRandomNumbersWithinRange(0,25,5) ); ?>
Result:
Array ( [0] => 14 [1] => 16 [2] => 17 [3] => 20 [4] => 1 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With