Skip to content

Instantly share code, notes, and snippets.

@cevin
Created December 20, 2017 13:30
Show Gist options
  • Save cevin/38ca6a464196ba88b746a04fe00fff68 to your computer and use it in GitHub Desktop.
Save cevin/38ca6a464196ba88b746a04fe00fff68 to your computer and use it in GitHub Desktop.
最优匹配
<?php
$rand = [20,15,10,6];
$r = 39;
function combination($a, $m) {
$r = array();
$n = count($a);
if ($m <= 0 || $m > $n) {
return $r;
}
for ($i=0; $i<$n; $i++) {
$t = array($a[$i]);
if ($m == 1) {
$r[] = $t;
} else {
$b = array_slice($a, $i+1);
$c = combination($b, $m-1);
foreach ($c as $v) {
$r[] = array_merge($t, $v);
}
}
}
return $r;
}
$sets = [];
for ($i=1,$j=count($rand);$i<$j;$i++){
foreach(combination($rand, $i) as $v) {
$sets[implode(',',$v)] = abs($r - array_sum($v));
}
}
asort($sets);
echo "序列:".implode(',', $rand).", 匹配:{$r}\n";
echo "最优: ".key($sets).", 误差: ".current($sets)."\n";
print_r($sets);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment