I am managing a function that can vary a range_pool of numbers with set decimals between them. I would like to find a solution that ensures that these numbers never repeat (create duplicates) when they are generated at the exit of the function.
`function random($min, $max, $range_pool) {
$decimals = 4;
$collect_range_pool = array();
for ($i = 0; $i < $range_pool; $i++)
{
$random_number = mt_rand() / mt_getrandmax();
$range = $max - $min;
$random_decimal = $min + $random_number * $range;
$random_decimal = round($random_decimal, $decimals);
$collect_range_pool[] = $random_decimal;
}
return $collect_range_pool;
}
$generated = random(4.0008, 4.1008, 20);
foreach ($generated as $number)
{
echo $number . '<br>';
}`
I am expecting for the number to never repeat.
3
Answers
use
array_unique()
:A simple way is to check if a value has already been drawn, and ignore it if it has:
Output:
If pool size is not going to be huge (i.e. you don’t need to care too much about optimisation), you can go the easy route and use an associative array. The key can be the number itself normalised to the exact number of decimals: