4

Here is an array.

$item = array('A', 'B', 'C', 'D');

I want to list all possible orders in this array like:

A
A,B
A,B,C
A,B,C,D
A,C
A,C,D
A,C,B
...
B,A
B,A,C
....

How can I do that?

Kit
  • 105
  • 3
  • 7
  • 1
    Is this homework, if so please add the `homework` tag. – home Jan 16 '12 at 09:29
  • I think you should try yourself... try googling recursivity and permutation – de3 Jan 16 '12 at 09:30
  • There is nothing special about `php` in this problem. Its a general algorithm. You just need to know the algorithm. You can say "in php" IMO if you show us what codes you have written till now. – footy Jan 16 '12 at 09:31
  • 1
    First result on Google: http://www.hashbangcode.com/blog/getting-all-permutations-array-php-74.html – Quasdunk Jan 16 '12 at 09:33
  • 2
    I dont understand why this question has up votes.... – footy Jan 16 '12 at 09:36
  • possible duplicate of [Permutations - all possible sets of numbers](http://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers) – zaf Jan 16 '12 at 09:45

2 Answers2

2

The permutations you want to know can be accomplished through this algorithm and applying in a loop for the subsets.

Initialize the first permutation with <1 <2 ...

while there exists a mobile integer

find the largest mobile integer k

swap k and the adjacent integer it is looking at

reverse the direction of all integers larger than k

Refer to this question for more info

Community
  • 1
  • 1
footy
  • 5,803
  • 13
  • 48
  • 96
1

You can use this recursive function:

function recursive_permutations($items,$perms = array( ))
{
 static $list;
 if (empty($items)) {
  $list[] = join(',', $perms);
 } else {
  for ($i = count($items)-1;$i>=0;--$i) {
   $newitems = $items;
   $newperms = $perms;
   list($foo) = array_splice($newitems, $i, 1);
   array_unshift($newperms, $foo);
   recursive_permutations($newitems, $newperms);
  };
  return $list;
 };
}
$perms = recursive_permutations(array('A', 'B', 'C', 'D'));
echo '<pre>' . print_r($perms, true) . '</pre>';
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143