php一组数字分成两组,使他们的和最接近(和的差最小)
<?phpfunction groupTwo($arr) {
$n = count($arr);
$v = array();
$nice = array();
for($i = 1; $i < $n - 1; $i++ ) {
$group1 = [];
$group2 = [];
for($j = 0; $j < $n; $j++ ) {
$group1 = array_slice($arr, $j, $i, true);
$group2 = array_diff_key($arr, $group1);
$diff[] = abs(array_sum($group1) - array_sum($group2));
$all[] = array($group1, $group2);
}
}
asort($diff);
$zu = array_shift(array_keys($diff));
return $all[$zu];
}
$arr = ;
$best = groupTwo($arr);
print_r($best);
页:
[1]