Malik Drako - 5 months ago 14

PHP Question

What is the best way to generate a random integer with a restricted set of digits?

I want to generate a 4 digit random number, where each digit is in the range [1..6]. I was thinking generate a number in the range [0..1295], then converting to base 6 and incrementing the digits, but that goes through a string.

Answer

Without string conversion, and with only one call to a random number generator, you could do this:

```
function myRandom() {
$num = mt_rand(0, 1295);
$result = 0;
for ($i = 0; $i < 4; $i++) {
$result = $result*10 + $num % 6;
$num = floor($num / 6);
}
return $result + 1111;
}
```