Suitable algorithm for combinations of numbers in an array

86
May 14, 2018, at 9:10 PM

I have a PHP project where I need to work out all of the combinations of an indeterminate amount of numbers (stored in an array) (but usually no greater than 5) and store them in a separate array.

e.g. (not using PHP syntax):

numbers = (1 2 3)
1 + 2 = 3
1 + 3 = 4
2 + 3 = 5
1 + 2 + 3 = 6

which would create an array of:

3,4,5,6

A second example would be:

numbers = 1 2 3 4
1 + 2 = 3
1 + 3 = 4
1 + 4 = 5
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
2 + 3 = 5
2 + 4 = 6
2 + 3 + 4 = 9
3 + 4 = 7

I have tried modifying the code found at: https://r.je/php-find-every-combination.html

but I seem to be not be getting the correct output, this is my reduced code without pushing to an array:

$nums = array(1, 2, 3);   
$num = count($nums); 
$total = pow(2, $num);
$test = 0;

for ($i = 0; $i < $total; $i++) {  
    //For each combination check if each bit is set 
    for ($j = 0; $j < $num; $j++) { 
       //Is bit $j set in $i?

        if (pow(2, $j) & $i) {
          $test += $nums[$j];

        }
    } 
    echo $test . ',';
}

This outputs: 0,1,3,6,9,13,18,24,

If anyone knows of a good method of achieving this it would be much appreciated.

Answer 1

At the end of your for, put your $test var to 0

$nums = array(1, 2, 3);   
$num = count($nums); 
$total = pow(2, $num);
$test = 0;

for ($i = 0; $i < $total; $i++) {  
    //For each combination check if each bit is set 
    for ($j = 0; $j < $num; $j++) { 
       //Is bit $j set in $i?

        if (pow(2, $j) & $i) {
          $test += $nums[$j];

        }
    } 
    echo $test . ',';
    $test = 0;
}

[EDIT]

mmm... minus 0, this is the result:

0, 1(1), 2(2), 3(3), 3(1+2), 4(1+3), 5(2+3), 6(1+2+3),
READ ALSO
Dynamic_sidebar load in string makeup

Dynamic_sidebar load in string makeup

in my theme the header is loaded through a string (i think thats correct) like below and iv been trying to add a sidebar into it but its only showing the number '1' ?

67
100% Java NaCl sign and verification

100% Java NaCl sign and verification

Is there currently a 100% Java way to use NaCl encryption ? I'd like very much to get rid of the native Sodium library

101
How to run node.js application on pm2

How to run node.js application on pm2

I am new to pm2 manager and sshI developed one project in node

145
How to download PDF file using URL in angularJS

How to download PDF file using URL in angularJS

How to download a PDF file using file URLI am tried many eg, but no luck

14