Replace duplicate values in array with new randomly generated values
Posted
by RussellDias
on Stack Overflow
See other posts from Stack Overflow
or by RussellDias
Published on 2010-05-08T15:15:45Z
Indexed on
2010/05/08
15:18 UTC
Read the original article
Hit count: 187
php
I have below a function (created by Gordon in a previous question that went unanswered) that creates an array with n amount of values. The sum of the array is equal to $max.
function randomDistinctPartition($n, $max)
{
$partition= array();
for($i=1; $i < $n; $i++) {
$maxSingleNumber = $max - $n;
$partition[] = $number = rand(1, $maxSingleNumber);
}
$max -= $number;
}
$partition[] = $max;
return $partition;
}
For example: If I set $n = 4 and $max = 30. Then I should get the following.
array(5, 7, 10, 8);
However, this function does not take into account duplicates and 0s. What I would like - and have been trying to accomplish - is to generate an array with unique numbers that add up to my predetermined variable $max. No Duplicate numbers and No 0 and/or negative integers.
© Stack Overflow or respective owner