我的问题的引用
how can I get the closest pairs from this array
// Input
$required = 1.3;
$array_result = [0.6, 0.5, 0.8, 0.7];
// Algorithm
$remaining = $required;
$whichtakes = [];
foreach($array_result as $i => $a) {
foreach(array_slice($array_result, $i+1) as $b) {
$test = $required - $a - $b;
if ($test >= 0 and $test < $remaining) {
$remaining = $test;
$whichtakes = [$a, $b];
}
}
}
// Output
print_r($whichtakes); // [0.5, 0.8]
print_r($remaining); // 0
感谢小装饰品
它可以很好地与线对一起工作,但是变化很小,算法正在获取线对,但是我想要与我的结果数组匹配的数组,只需要这个小小的变化。如果$ required = 1.3更改为$ required = 1.8,现在应该给我数组0.6,0.5,0.7,如果$ required = 1.9现在,应该给我剩余的数组0.6,0.5,0.7和0.1
答案 0 :(得分:0)
此算法是动态编程的一部分。这是修改后的代码。
$res = array();
function isSubsetSum($set, $n, $sum)
{
if ($sum == 0)
return true;
if ($n == count($set) - 1 && $sum != 0)
return false;
if ($set[$n + 1] > $sum) {
return isSubsetSum($set, $n + 1, $sum);
}
return isSubsetSum($set, $n + 1, $sum) ||
isSubsetSum($set, $n + 1, $sum - $set[$n + 1]);
}
$set = array(0.6, 0.5, 0.8, 0.7);
$sum = 1.8;
$n = 0;
$remaining = 0;
while (!isSubsetSum($set, 0, $sum)) {
$remaining += 0.1;
$sum -= 0.1;
}
echo $res; // the array result
echo $remaining;
此代码不存储数组子集。您可以将数组结果存储在函数中。不过,我不知道如何优化此算法。
有关动态编程的更多信息,请检查此link