📜 ⬆️ ⬇️

Completely random numbers without repeating

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 :


UPD


Thanks to duncanf1 for an even shorter version:
function generateRandomNumber ($maximum, $count){
return array_rand(range(0, $maximum), $count);
}

Source: https://habr.com/ru/post/54326/


All Articles