8

Possible Duplicate:
algorithm that will take numbers or words and find all possible combinations

If I have an array such as:

array('a', 'b', 'c', 'd');

How would I create a new array with all possible combinations of those 4 values such as

aaaa, aaab, aaac, aaad ... dddb, dddc, dddd

Thanks!

Community
  • 1
  • 1
user1926784
  • 83
  • 1
  • 3

2 Answers2

9

Here's another way.

This function increments in base( [number of elements in array] )

and uses the strtr function to swap out the characters for strings.

function everyCombination($array) {

    $arrayCount      = count($array);
    $maxCombinations = pow($arrayCount, $arrayCount);
    $returnArray     = array();
    $conversionArray = array();

    if ($arrayCount >= 2 && $arrayCount <= 36)
    {
        foreach ($array as $key => $value) {
            $conversionArray[base_convert($key, 10, $arrayCount)] = $value;
        }

        for ($i = 0; $i < $maxCombinations; $i++) {
            $combination    = base_convert($i, 10, $arrayCount);
            $combination    = str_pad($combination, $arrayCount, "0", STR_PAD_LEFT);
            $returnArray[]  = strtr($combination, $conversionArray);
        }

        return $returnArray; 
    }

    echo 'Input array must have between 2 and 36 elements';
}

Then ...

print_r(everyCombination(array('a', 'b', 'c', 'd')));

This also seems to be significantly faster than the recursive example below.

Using microtime() on my server this code runs in 0.072862863540649 seconds

The recursive example below takes 0.39673089981079 seconds.

138% faster!

Andrew Phillips
  • 324
  • 2
  • 8
4

You should use a recursive function

function perm($arr, $n, $result = array())
{
    if($n <= 0) return false;
    $i = 0;

    $new_result = array();
    foreach($arr as $r) {
    if(count($result) > 0) {
        foreach($result as $res) {
                $new_element = array_merge($res, array($r));
                $new_result[] = $new_element;
            }
        } else {
            $new_result[] = array($r);
        }
    }

    if($n == 1) return $new_result;
    return perm($arr, $n - 1, $new_result);
}

$array = array('a', 'b', 'c', 'd');
$permutations = perm($array, 4);
print_r($permutations);
BenMorel
  • 34,448
  • 50
  • 182
  • 322
ahmetunal
  • 3,930
  • 1
  • 23
  • 26