I'm want to write function that returns next permutation in lexicographic order n choose k.
So far I found following algorithm
class Permutation
{
public function swap(& $a, $first, $second)
{
$tmp = $a[$first];
$a[$first] = $a[$second];
$a[$second] = $tmp;
}
function nextPermutation(& $a, $n, $k)
{
do {
$first = $n - 2;
while ($first != -1 && $a[$first] >= $a[$first + 1]) $first--;
if ($first == -1)
return false;
$second = $n - 1;
while ($a[$first] >= $a[$second]) $second--;
$this->swap($a, $first, $second);
$left = $first + 1;
$right = $n - 1;
while ($left < $right) {
$this->swap($a, $left++, $right--);
}
} while ($first > $k - 1);
return true;
}
public function run()
{
$n=10;
$k=4;
$a = array_merge(range(ord(0), ord(9)), range(ord('A'), ord('Z')), range(ord('a'), ord('z')));
$i = 0;
while ($this->nextPermutation($a, $n, $k)) {
$i++;
echo($i . ") ");
for ($j = 0; $j < $k; $j++) {
echo $a[$j] . " ";
}
echo("\n");
}
}
}
But it works only with n up to 13 and then gets every slow. I need to make it work for n=62 and k=6. Is it possible to do it?