Create dynamic for loop PHP function for all potential combinations

Go To StackoverFlow.com

1

The code below will create an array for all possible combination that can occur when you have four different variables. The variables always need to equal 1. The for loops I have created work and I understand how to make this work for more variables, but can I make this dynamic? I need to have a function that has how many variables there are as a parameter. If there are three variables create the three forloops. If there are 10... create the 10 corresponding for loops to determine all possible combinations.

$anarray2 = array();
for( $a = 1; $a <= 97; $a++ ) {
  for( $b = 1; $a + $b <=98 ; $b++ ) {
    for( $c = 1; $a + $b + $c <= 99; $c++ ) {
      $d = 100 - ( $a + $b + $c );
      $var_1 = $a / 100;
      $var_2 = $b / 100;
      $var_3 = $c / 100;
      $var_4 = $d / 100;
      $anarray2[] = array( $var_1, $var_2, $var_3, $var_4 );
    }
  }
}
print_array( $anarray2 );
2012-04-04 02:08
by Jason Biondo
Are you looking for a cartesian product algorithm? There are already many out there.. - deceze 2012-04-04 02:16
Can you provide me with a link to an example? I've never heard of this before.... time to google - Jason Biondo 2012-04-04 03:07
Start here: http://stackoverflow.com/search?q=%5Bphp%5D+cartesian+product+algorith - deceze 2012-04-04 03:14
I think you're probably right, but I'm not sure about the implementation. I'll keep looking.. - Jason Biondo 2012-04-04 04:41


0

You're effectively looking to share out I identical items to N people in all of the different possible ways.

If there is one person (N==1), then there is only one way to do this - give that person all I items.

If there is more than one person (N>1), then we can consider how many items can be assigned to the first person, and then what the possible assignments are for the remaining N-1 people in each case.

This leads to a nice recursive solution. Firstly we solve the problem for N=1:

function assign($I, $N) {
    $anarray = array();

    if ($N == 1) {
        $anarray[] = array($I);
    } else {
        // Coming up...
    }

return $anarray;
}

Now we solve the problem for N=k (some constant) in terms of N=k-1 - that is, we solve the problem using the solution to a smaller problem. This will reach all the way back to the solution when N=1.

function assign($I, $N) {
    $anarray = array();

    if ($N == 1) {
        $anarray[] = array($I);
    } else {
        for ($i = $I; $i < $I; $i++) {
            foreach (assign($I - $i, $N - 1) as $subproblem) {
                $anarray[] = array_merge(array($i), $subproblem);
            }
        }
    }

    return $anarray;
}    

Something like that should do the job.

2012-06-06 11:44
by Eliot Ball