Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random integer with conditions

Tags:

php

random

I have a PHP script where I have an array of integers, let's say $forbidden.

I want to get a random integer from 1 to 400 that is not in $forbidden.

Of course, I don't want any loop which breaks when rand gives a working result. I'd like something more effective.

How do you do this ?

like image 231
Cydonia7 Avatar asked May 03 '12 20:05

Cydonia7


People also ask

How do you generate a random number in Python with conditions?

Another method to generate a floating random number is by using the random() function. The random() function does not take any arguments. It will generate a floating-point random number between the range 0 and 1 where 1 is not included in the output. The range is defined as: [0.0, 1.0).

What is random integer?

A random number is a number chosen as if by chance from some specified distribution such that selection of a large set of these numbers reproduces the underlying distribution. Almost always, such numbers are also required to be independent, so that there are no correlations between successive numbers.

Does random () include 0?

Math. random() can never generate 0 because it starts with a non-zero seed. Set the seed to zero, the function does not work, or throws an error. A random number generator always returns a value between 0 and 1, but never equal to one or the other.


1 Answers

Place all forbidden numbers in an array, and use array_diff from range(1,400). You'll get an array of allowed numbers, pick a random one with array_rand().

<?php

$forbidden = array(2, 3, 6, 8);
$complete = range(1,10);
$allowed = array_diff($complete, $forbidden);

echo $allowed[array_rand($allowed)];

This way you're removing the excluded numbers from the selection set, and nullifying the need for a loop :)

like image 190
Madara's Ghost Avatar answered Oct 16 '22 19:10

Madara's Ghost