Jump to content

mt_rand to never pick 2 values of equal value?


Monkuar

Recommended Posts

function choose_numbers($number,$max) {
		global $ibforums,$std;
		srand( (double)microtime() * 1000000 );
		$array = array();
		$i = 0;
		while($i!=$number)
		{
		$array[] = mt_rand(1,$max);
		$i++;
		}
		$c = count($array);
		while($c != $number)
		{
		$array[] = mt_rand(1,$max);
		$c = count($array);
		if($c == $number)
		{
		$array = array_unique($array);
		$c = count($array);
		}
		}
		return $array;
	}
$newnumbers = $this->choose_numbers(3,36);
echo "{$newnumbers['0']}|{$newnumbers['1']}|{$newnumbers['2']}";

 

This echo's out my lottery balls 0|32|22 or technically RANDNuMbER|RANDNUMBER|RANDNUMBER

 

up to 36 is the highest number.

 

Now my issue is, I don't want 2 numbers of the same Value, EVER. Sometimes it does 2|3|2 which is BAD (for my lottery system) is there anyway I can make it so it never will echo out 2 (OR 3) of the same number?

1. if you are running any PHP version greater than 4.2.0, srand() is not needed.

 

2. don't use the global keyword, you don't even use those variables in your function.

 

3. I would check for the existence of the random value in the array before inserting, making sure that all values will be unique.

 

$array = array();
$i = 0;
while($i != $number)
{
$rand = mt_rand(1,$max);
if(!in_array($rand,$array))
   $array[] = $rand;
$i++;
}
return $array;

1. if you are running any PHP version greater than 4.2.0, srand() is not needed.

 

2. don't use the global keyword, you don't even use those variables in your function.

 

3. I would check for the existence of the random value in the array before inserting, making sure that all values will be unique.

 

$array = array();
$i = 0;
while($i != $number)
{
$rand = mt_rand(1,$max);
if(!in_array($rand,$array))
   $array[] = $rand;
$i++;
}
return $array;

 

1 Problem

 

sometimes it displays 1 missing number as a blank?

 

"17|29|"

 

 

Yes, that's because the counter is incremented irrespective of whether the generated random number was in the array or not. Write the if() conditional in standard format, with curly braces, and move the $i++ within the curly braces. That should take care of it.

Yes, that's because the counter is incremented irrespective of whether the generated random number was in the array or not. Write the if() conditional in standard format, with curly braces, and move the $i++ within the curly braces. That should take care of it.

 

if(!in_array($rand,$array)) {
   $array[] = $rand;
$i++;
}

 

Marked as Resolved.

 

Kudos.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.