Skip to content

Instantly share code, notes, and snippets.

@guibranco
Created December 16, 2021 11:53
Show Gist options
  • Save guibranco/69701a555571a06cb63afbfdd1646923 to your computer and use it in GitHub Desktop.
Save guibranco/69701a555571a06cb63afbfdd1646923 to your computer and use it in GitHub Desktop.
Soma de valores mais proximos de um valor final - PHP Brasil - Alan Cisneiro - https://www.facebook.com/groups/phpbr/posts/4765496826840537/
<?php
$nfs = array(100,600,300,400);
$max = 1000;
$minDist = null;
$minDistI = null;
$maxI = pow(2,sizeof($nfs));
for($i=0;$i<$maxI;$i++) {
$soma = 0;
for($j=0;$j<sizeof($nfs);$j++) {
if($i & (1 << $j))
$soma += $nfs[$j];
}
$dife = abs($soma - $max);
if($minDistI === null || $dife < $minDist) {
$minDistI = $i;
$minDist = $dife;
}
if($dife == 0)
break;
}
$final = array();
for($j=0;$j<sizeof($nfs);$j++)
if($minDistI & (1 << $j))
$final[] = $nfs[$j];
echo implode(",", $final);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment