Created
December 20, 2017 13:30
-
-
Save cevin/38ca6a464196ba88b746a04fe00fff68 to your computer and use it in GitHub Desktop.
最优匹配
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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