PHP: permutations formula

Finding All Permutations of an Array, nPk = n!/(n-k)!:

function pc_permute($items, $perms = array( )) {
  if (empty($items)) {
    print 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);
      pc_permute($newitems, $newperms);
    }
  }
}
 
$p = pc_permute(array(1, 2, 3, 4));
print join(',', $p) . "
 
";

Leave a Reply