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.
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:
function random(float $min, float $max, int $range_pool): array
{
$decimals = 4;
$collect_range_pool = [];
$count = 0;
while ($count < $range_pool) {
$random_number = mt_rand() / mt_getrandmax();
$range = $max - $min;
$random_decimal = $min + $random_number * $range;
$random_decimal = round($random_decimal, $decimals);
$key = number_format($random_decimal, $decimals, '.', '');
if (!array_key_exists($key, $collect_range_pool)) {
$collect_range_pool[$key] = $random_decimal;
$count++;
}
}
return array_values($collect_range_pool);
}