Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

all combination of x pow y in php

I have an array having three element $base =(#m, #f,#p)

I have a second array having any number of element like $var = (s1, s2)

Now i need to create all possible combinations depending only on the base array. The formula I found is x pow y.

In this example my base array has three element and $var has 2, so pow(3, 2) is 9. I need these nine combinations. i.e

#m#m #m#f #m#p
#f#m #f#f #f#p
#p#m #p#f #p#p

The number of elements in the 2nd array is in effect the length of the generated combinations. As in this example the length of the 2nd array is 2 so all generated strings have length 2.

like image 305
user1635914 Avatar asked Sep 11 '12 12:09

user1635914


1 Answers

You can use a recursive function like this:

// input definition
$baseArray = array("#m", "#f", "#p");
$varArray = array("s1", "s2", "s3");

// call the recursive function using input
$result = recursiveCombinations($baseArray, sizeof($varArray));

// loop over the resulting combinations
foreach($result as $r){
    echo "<br />combination " . implode(",", $r);
}

// this function recursively generates combinations of #$level elements
// using the elements of the $base array
function recursiveCombinations($base, $level){
    $combinations = array();
    $recursiveResults = array();

    // if level is > 1, get the combinations of a level less recursively
    // for level 1 the combinations are just the values of the $base array
    if($level > 1){
        $recursiveResults = recursiveCombinations($base, --$level);
    }else{
        return $base;   
    }
    // generate the combinations
    foreach($base as $baseValue){
        foreach($recursiveResults as $recursiveResult){
            $combination = array($baseValue);
            $combination = array_merge($combination, (array)$recursiveResult);  
            array_push($combinations, $combination);
        }
    }
    return $combinations;
}

Working codepad demo

like image 130
Asciiom Avatar answered Sep 28 '22 06:09

Asciiom