Reputation: 35
Is it possible to generate a random number based on a condition?
I would like to generate a random number, 1-1000. However, I do not want the same random value to generate any number that is already present within my variables
<?php
$low= 0;
$height= 1000;
$num_1 =1;
$num_2 =3;
$num_3 =4;
$num_4 =6;
$num_5 =2;
$num = rand($low, $height) & != ($num_1 - $num_5) ;
?>
Upvotes: 0
Views: 1865
Reputation: 477
From what I understand I think you are implying that you need UNIQUE random numbers to variables.
Although for your case of five numbers you can use the solution provided above, yet the solution does not gurantee smooth running (what if the rand function were to return the same number indefinitely, though practically least possible for large numbers).
ALGORITHM:
low = 0
height = 1000
val = array(1,2,3,4,5,....1000)// better not to waste cycles generating them
i=0
while(i<5)
{
t = rand(low , height);
num[i] = val[t];
val[t] = val[height];
i++;
height--;
}
Upvotes: 1
Reputation: 24825
$low= 0;
$height= 1000;
$numbers = array(1, 3, 4, 6, 2);
$num = rand($low, $height);
while (in_array($num, $numbers)) {
$num = rand($low, $height);
}
I am assuming that adding your 'not allowed' values to an array would be more efficient?
Upvotes: 1
Reputation: 1715
Bear with this long conditional:
$num = rand($low, $height);
while($num == $num_1 || $num == $num_2 || $num == $num_3 || $num == $num_4 || $num == $num_5){
$num = rand($low, $height);
}
Upvotes: 0