How can I get all permutations in PHP without successive duplicates?

This question has been asked in many forms. I want to take an array in PHP and get all possible combinations / permutations. I want both permutations of the entire set, and a partial set.

My twist on this question asks how can I remove consecutive duplicates from result elements. I got closer to what I wanted, using PHP all combinations "and adding a function:

$words = array('a','b','c'); function permutations($arr,$n) { $res = array(); foreach ($arr as $w) { if ($n==1) $res[] = $w; else { $perms = permutations($arr,$n-1); foreach ($perms as $p) { $res[] = $w." ".$p; } } } return $res; } function get_all_permutations($words=array()) { $r = array(); for($i=sizeof($words);$i>0;$i--) { $r = array_merge(permutations($words,$i),$r); } return $r; } $permutations = get_all_permutations($words); print_r($permutations); 

This will output:

 Array ( [0] => a [1] => b [2] => c [3] => aa [4] => ab [5] => ac [6] => ba [7] => bb [8] => bc [9] => ca [10] => cb [11] => cc [12] => aaa [13] => aab [14] => aac [15] => aba [16] => abb [17] => abc [18] => aca [19] => acb [20] => acc [21] => baa [22] => bab [23] => bac [24] => bba [25] => bbb [26] => bbc [27] => bca [28] => bcb [29] => bcc [30] => caa [31] => cab [32] => cac [33] => cba [34] => cbb [35] => cbc [36] => cca [37] => ccb [38] => ccc ) 

I know that I could view the result after creating the set, but is it possible to remove successive duplicates during generation?

Examples to be converted / deleted:

  • ccc will be the same as c
  • ccb will be the same as cb
  • ccccc will also be the same as c (if the set was larger)

Notes:

  • I'm not very good with recursion, but there is probably a fantastic way to combine the two functions that I have in one.
  • Now the output sets are strings, but I don't mind if they are arrays instead (if this makes the task easier)
+2
source share
1 answer

You can pass an array of permutations as reference (followed by an ampersand) as the third permutation parameter () and do a in_array () before adding the value. However, this would be much less productive than removing duplicates at the end of get_all_permutation ()

0
source

All Articles