fork(24) download
  1. <?php
  2. static $values = array( 15.92, 53.27, 244.28, 388.46, 3.14, 2.92, 18.22, 4.03 );
  3. static $expected = 297.55;
  4. static $precision = 100; /* para não ter problemas com ponto flutuante */
  5.  
  6. $target = floor( $expected * $precision );
  7. $len = count( $values );
  8. for( $i = 1; $i < pow( 2, $len ); $i++ ) {
  9. $soma = 0;
  10. $set = array();
  11. for( $j = 0; $j < $len; $j++ ) {
  12. if( 1 << $j & $i ) {
  13. $set[] = $j;
  14. $soma += floor( $values[$j] * $precision );
  15. }
  16. }
  17. if( $soma == $target ) {
  18. // Estamos exibindo na tela apenas como demonstração. Se preferir pode armazenar.
  19. foreach( $set as $pos ) echo "[$pos]{$values[$pos]} ";
  20. echo " = $expected\n";
  21. }
  22. }
  23. ?>
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
[1]53.27 [2]244.28  = 297.55