Created
December 16, 2021 11:53
-
-
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/
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 | |
$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