Skip to content

Instantly share code, notes, and snippets.

@diogoca
Created April 5, 2018 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diogoca/9bb05fc7d0979ddaea77228c78d9f40d to your computer and use it in GitHub Desktop.
Save diogoca/9bb05fc7d0979ddaea77228c78d9f40d to your computer and use it in GitHub Desktop.
Encontrar soma em uma lista de possíveis arrays
<?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