How to find all possible orders with an array element

Here is the array.

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

I want to list all possible orders in this array, for example:

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 this?

+4
source share
2 answers

permutations that you want to know can be done using this algorithm and applying in a loop for subsets.

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

while there is a mobile integer

find the largest integer k

swap k and the adjacent whole that he is looking for

change the direction of all integers greater than k

Refer to this question for more information.

+1
source

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>'; 
+1
source

Source: https://habr.com/ru/post/1391225/


All Articles