Created
April 5, 2018 14:19
-
-
Save diogoca/9bb05fc7d0979ddaea77228c78d9f40d to your computer and use it in GitHub Desktop.
Encontrar soma em uma lista de possíveis arrays
This file contains hidden or 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 | |
static $values = array( 15.92, 53.27, 244.28, 388.46, 3.14, 2.92, 18.22, 4.03 ); | |
static $expected = 297.55; | |
static $precision = 100; /* para não ter problemas com ponto flutuante */ | |
$target = floor( $expected * $precision ); | |
$len = count( $values ); | |
for( $i = 1; $i < pow( 2, $len ); $i++ ) { | |
$soma = 0; | |
$set = array(); | |
for( $j = 0; $j < $len; $j++ ) { | |
if( 1 << $j & $i ) { | |
$set[] = $j; | |
$soma += floor( $values[$j] * $precision ); | |
} | |
} | |
if( $soma == $target ) { | |
// Estamos exibindo na tela apenas como demonstração. Se preferir pode armazenar. | |
foreach( $set as $pos ) echo "[$pos]{$values[$pos]} "; | |
echo " = $expected\n"; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment