问题
Say I have an array [10000,5000,1000,1000] and I would like to find the closest sum of numbers to a given number. Sorry for the bad explanation but here's an example:
Say I have an array [10000,5000,1000,1000] I want to find the closest numbers to, say 6000.
Then the method should return 5000 and 1000
another example : we want the closest to 14000 , so then he should return 10000 and 5000
here i've tried on php but it's something wrong when i put 6000 i should get 5000 and 1000
<?php
$arr = [10000,5000,1000,1000];
$x = 6000;
var_dump(eek($x,$arr));
function eek($x,$arr)
{
$index = [];
$counter = 0;
foreach($arr as $val)
{
if($counter + $val <= $x)
{
$counter += $val;
$index[] = $val;
}
elseif($counter + $val >= $x)
{
$counter += $val;
$index[] = $val;
break;
}
}
if($counter == $x)
{
return $index;
}
elseif($counter >= $x)
{
return $index;
}
else
{
return [];
}
}
?>
Anyone have solution about it ?
回答1:
Here it is works with float and negative values:
$numbers = array(
10000,5000,1000,1000
);
$desiredSum = 6000;
$minDist = null;
$minDist_I = null;
// Iterate on every possible combination
$maxI = pow(2,sizeof($numbers));
for($i=0;$i<$maxI;$i++) {
if(!(($i+1) % 1000)) echo ".";
// Figure out which numbers to select in this
$sum = 0;
for($j=0;$j<sizeof($numbers);$j++) {
if($i & (1 << $j)) {
$sum += $numbers[$j];
}
}
$diff = abs($sum - $desiredSum);
if($minDist_I === null || $diff < $minDist) {
$minDist_I = $i;
$minDist = $diff;
}
if($diff == 0) break;
}
$chosen = array();
for($j=0;$j<sizeof($numbers);$j++) {
if($minDist_I & (1 << $j)) $chosen[] = $numbers[$j];
}
echo "\nThese numbers sum to " . array_sum($chosen) . " (closest to $desiredSum): ";
echo implode(", ", $chosen);
echo "\n";
回答2:
Taking in count that the array is ordered from bigger to smaller values
Here is a solution, starting from yours
function eek($x,$arr)
{
$index = [];
$counter = 0;
foreach($arr as $key => $val) {
if($counter + $val < $x) {
$counter += $val;
$index[] = $val;
} else {
if (isset($arr[$key+1]) && (abs($counter + $arr[$key+1] -$x) < abs($counter + $val -$x))) {
continue;
} else {
$index[] = $val;
return $index;
}
}
}
return $index;
}
来源:https://stackoverflow.com/questions/58918556/find-nearest-sum-of-numbers-in-array-to-a-given-number