-1

I need help looping through a simple array and find all possible combination of its elements like this:

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

Expected result is:

array(
     0=>array('a', 'a', 'a'),
     1=> array('a', 'a', 'b')
);

I'm at a complete loss and any help or pointers is much appreciated!

This is what I have so far.

$array = array('red', 'blue', 'green', 'white');
$count = count($array);

$current = array_fill(0, $count, $array[0]);
$last = array_fill(0, $count, end($array));


$output = array();
$i = 0;

while ($current != $last) {
    $indexes = str_pad($i, $count, "0", STR_PAD_LEFT);

    $j = str_split($indexes);

    foreach ($j as $a => $b) {
        if (isset($array[$b])) {
            $output[$i][] = $array[$b];
        }
    }
    $current = $output[$i];
    $i++;
}
// cleaver duplication removal
$result = array_map("unserialize", array_unique(array_map("serialize", $output)));

echo '<pre>';
    print_r($result);
echo '</pre>';

Duplicate removal code is from here.

Community
  • 1
  • 1
user389767
  • 73
  • 1
  • 9
  • 2
    Hello and welcome to StackOverflow. While you may be having trouble with your program, we highly encourage (and insist) that you give it your best shot before asking the community for help. When it's clear that you're running into issues with code that you've tried, we're glad to help! If you don't put any effort into designing your own solutions, we tend to down-vote your question and close it. You must at least attempt a solution first. Never ask someone else to write code in lieu of an honest effort. In short, [what have you tried](http://www.whathaveyoutried.com)? – Matt Aug 29 '12 at 18:50
  • Hi Matt. Sorry for not including my work in progress in the question. I'll add it as one of the answer. It works but it really is a very lazy way to go, nothing cleaver and fancy. If the source array is big it will probably go over the memory limit. – user389767 Aug 30 '12 at 17:18
  • You need to iterate through the array, recursively examining the possible combinations of the elements to the right of your pointer with the current element. Be warned that this will take both time and memory roughly proportional to n! so don't use it on large arrays. – Terence Johnson Aug 30 '12 at 17:31

1 Answers1

1
function pc_permute($items, $perms = array( )) {
    if (empty($items)) { 
        print join(' ', $perms) . "\n";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

Source.

Marcelo Assis
  • 5,136
  • 3
  • 33
  • 54
  • Thanks for the permutation function. However I'm not looking for permutation, I need repetitions. It's a good start tho. – user389767 Aug 30 '12 at 17:30