Posted By

trusktr on 04/28/11


Tagged

php permutations


Versions (?)

Permutations in PHP.


 / Published in: PHP
 

A recursive function to permute the items of an array. The function returns an array that contains many arrays, where each array is a permutation of the original array. This process can get intensive depending on how many items are in the initial array and how big the array items are.

  1. function permute(&$arr) { // permute the items in an array (n items, n at a time)
  2. static $perms = array(); static $usedItems = array();
  3. for ($i = 0; $i < sizeof($arr); $i++) {
  4. $item = array_splice($arr, $i, 1); //take item out
  5. $usedItems[] = $item[0];
  6. if (sizeof($arr) == 0) { // we have one permutation
  7. $perms[] = $usedItems; // add the result to our results container
  8. }
  9. permute($arr);
  10. array_splice($arr, $i, 0, $item[0]); //put item back
  11. array_pop($usedItems);
  12. }
  13. return $perms; // $perms contains arrays, each a permutation of the original array.
  14. }

Report this snippet  

You need to login to post a comment.