Friday, 10 August 2018

Getting All Permutations Of An Array In PHP


Here are two ways in which you can figure out all of the different permutations of an array.
The first is using a recursive algorithm. This nibbles apart the array and sticks it back together again, eventually resulting in all of the different permutations available.
  1. $list = array();
  2. function recursive_permutations($items,$perms = array( ))
  3. {
  4. static $list;
  5. if (empty($items)) {
  6. $list[] = join(',', $perms);
  7. } else {
  8. for ($i = count($items)-1;$i>=0;--$i) {
  9. $newitems = $items;
  10. $newperms = $perms;
  11. list($foo) = array_splice($newitems, $i, 1);
  12. array_unshift($newperms, $foo);
  13. recursive_permutations($newitems, $newperms);
  14. };
  15. return $list;
  16. };
  17. }
  18. $perms = recursive_permutations(range(1,3));
  19. echo '<pre>' . print_r($perms, true) . '</pre>';
The alternative is to use a force method that simply shuffles the array and then converts the resulting array pattern in a as a string. These strings are then used as keys for another array. After enough iterations the outer array should contain all of the permutations possible. This is by no means elegant or nice, but it works very well with smaller arrays.
  1. function permutations($array)
  2. {
  3. $list = array();
  4. for ($i=0; $i<=10000; $i++) {
  5. shuffle($array);
  6. $tmp = implode(',',$array);
  7. if (isset($list[$tmp])) {
  8. $list[$tmp]++;
  9. } else {
  10. $list[$tmp] = 1;
  11. }
  12. }
  13. ksort($list);
  14. $list = array_keys($list);
  15. return $list;
  16. }
  17. $perms = permutations(range(1, 3));
  18. echo '<pre>' . print_r($perms, true) . '</pre>';
Update 18/05/2011: 
Looking back at this code I can see that it is a little intensive as it will always run the array 10,000 times, even if all of the permutations have been found. To prevent it always running the full 10,000 iterations of the loop it is possible to find how many permutations would be found by working out the factorial of the length of the array. We can then stop the array once this limit has been reached.
  1. function permutations($array) {
  2. $list = array();
  3. $array_count = count($array);
  4. $number_of_permutations = 1;
  5. if ($array_count > 1) {
  6. for ($i = 1; $i <= $array_count; $i++) {
  7. $number_of_permutations *= $i;
  8. echo $number_of_permutations . ' ' . $i . "\n";
  9. }
  10. }
  11. for ($i=0; count($list) < $number_of_permutations; $i++) {
  12. shuffle($array);
  13. $tmp = implode(',', $array);
  14. if (!isset($list[$tmp])) {
  15. $list[$tmp] = 1;
  16. }
  17. }
  18. ksort($list);
  19. $list = array_keys($list);
  20. return $list;
  21. }

0 comments:

Post a Comment