Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating UNIQUE Random Numbers within a range

Tags:

php

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

like image 472
Sourav Avatar asked Apr 10 '11 15:04

Sourav


People also ask

How do you generate a random number from within a range?

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.


1 Answers

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 ) 
like image 179
Anne Avatar answered Sep 19 '22 09:09

Anne