PHP:查找X个可能值的列表,这些值的和给出Y个数



我想解决一个问题,但我不知道如何进行。

实际上,我想创建以下函数:

<?php
function xSumY(int $x, int $y)
{
$set = [];

//find $set {$a + $b + $c + ... ($x times)} which sum equal $y
}
//Examples 
$set1 = xSumY(55, 1);
$set2 = xSumY(1, 20);
$set3 = xSumY(3, 10); //returns for example {1, 3, 6}

注意:如果可能,避免重复给定值

提前感谢您的帮助。

我不明白你在回答中使用的所有代码的必要性。我在五分钟内完成了这个:

function xSumY(int $x, int $y)
{
if ($y < $x) die("xSumY(): Invalid input, y < x.");
$r = array_fill(1, $x, 1);
for ($i = 1; $i <= $y - $x; $i++) {
$r[random_int(1, $x)]++; 
}
return $r;
}

,它似乎做的工作。

几个小时后,我得到了这样的结果:

static function xSumY(int $x, int $y)
{
$setOf = []; //Will contain sum subset
$roundTo = strlen($x); //Will help to round values
if($x < 1 || $y < 1): //return empty array if null or negative values
return $setOf;
elseif($x == $y): //fill with same value if $x = $y
$setOf = array_fill(0, $x, ($x/$y));
return $setOf;
endif;
$maxRand = round($y/$x, $roundTo); //we are going to find a value between 0 and this
$multiplicator = pow((1 * 10), $roundTo+1);
$max = $maxRand * $multiplicator;

for($i=1; $i <= $x; $i++): //this loop help to create our set
if(count($setOf) + 1 == $x):
$currentElement = round(($y - array_sum($setOf)), $roundTo); //the last value of the set
else:
$currentElement = round(mt_rand(1, $max) / $multiplicator);
endif;
array_push($setOf, $currentElement); //add values to our set
endfor;
shuffle($setOf); //Make our set look more real
while(round((min($setOf) / max($setOf)) * 100) < 20): //Reduce the difference & avoid zero
$maxSet = max($setOf);
$maxIndex = array_search(max($setOf), $setOf);
$minSet = min($setOf);
$minIndex = array_search(min($setOf), $setOf);

$falsAverage = $maxSet + $minSet;
$newMin = round((mt_rand(2, 4) / 10) * $falsAverage);
$newMax = $falsAverage - $newMin;

$setOf[$maxIndex] = $newMax;
$setOf[$minIndex] = $newMin;
endwhile;
return $setOf; //Our set ready for use
}

我想知道它是好的,还是我遗漏了什么,或者是否有办法我可以更好地点。另外,我想知道这个操作是否会过度消耗内存。

最新更新