我有一个大约100个不同随机数的数组,如下所示:
$numbers=array(10,9,5,12, ..... .... ... ...);
现在我想使随机数的数组,从该数组使addition of selected numbers will be my given number
。例如:我可能会要求获取数字数组,例如if i add all numbers it will be 100
。我正在尝试通过这种方式
function rendom_num ($array,$addition)
{
//here is the code
}
print_r (rendome_num ($numbers,100));
我无法修改最近3天的代码!
这样的事情应该起作用。对该故障进行了注释,因此您知道它在做什么。
function Randomizer($number = 100)
{
// This just generates a 100 number array from 1 to 100
for($i=1; $i <= 100; $i++) {
$array[] = $i;
}
// Shuffles the above array (you may already have this array made so you would need to input into this function)
shuffle($array);
// Assign 0 as base sum
$sum = 0;
// Go through the array and add up values
foreach($array as $value) {
// If the sum is not the input value and is also less, continue
if($sum !== $number && $sum < $number) {
// Check that the sum and value are not greater than the input
if(($sum + $value) <= $number) {
// If not, then add
$sum += $value;
$new[] = $value;
}
}
// Return the array when value hit
else
return $new;
}
// If the loop goes through to the end without a successful addition
// Try it all again until it does.
if($sum !== $number)
return Randomizer($number);
}
// Initialize function
$test = Randomizer(100);
echo '<pre>';
// Total (for testing)
echo array_sum($test);
// Array of random values
print_r($test);
echo '</pre>';
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句