Task
Today I faced the task of making 4 random numbers in a given range, without repeating, it would seem such a trivial task, but!
The usual rand ($ min, $ max) did not give the desired result, especially with a small number of $ max ~ 15;
I.e:
$number[0] = rand(1, $max);
$number[1] = rand(1, $max);
$number[2] = rand(1, $max);
$number[3] = rand(1, $max);
Could end up giving out 2, 2, 3, 9 - I didn’t need these repetitions, asking for advice on the habrakanal,
freefd gave a link to the barley-style
cookbook , but I didn’t like the implementation because of its loudness and non-singularity.
')
Decision
As a result, having shown ingenuity, this solution appeared:
function generateFourRandomNumber ($maxCount){
$numbers = range(1, $maxCount);
shuffle($numbers);
return array($numbers[0], $numbers[1], $numbers[2], $numbers[3]);
}
Total
Voila! Simply lapidary, and even strange :)
few
BUT :
- the solution is suitable for small maximum values, otherwise the shuffle will then be too expensive
- the function is easy to remake by the form generateRandomNumber ($ maximum, $ count)
UPD
Thanks to
duncanf1 for an even shorter version:
function generateRandomNumber ($maximum, $count){
return array_rand(range(0, $maximum), $count);
}