Based on this question
Ordered Fixed Length Combination of a String
I created a PHP algorithm that creates combinations of characters on a fixed length (basically a rewrite of the Java-answer)
private function getCombination($length, $input) {
$result = array();
if ($length == 0) {
return $result;
}
$first = substr($input, 0, $length);
$result[] = $first;
if (strlen($input) == $length) {
return $result;
}
$tails = $this->getCombination($length - 1, substr($input, 1));
foreach ($tails as $tail) {
$tmp = substr($input, 0, 1) . $tail;
if (!in_array($tmp, $result)) {
$result[] = $tmp;
}
}
return array_merge($result, $this->getCombination($length, substr($input, 1)));
}
For another question, Create fixed length non-repeating permutation of larger set, I was given a (brilliant) algorithm that would make permutations indexable, effectively making them adressable by providing a "key" that would always produce the exact same permutation, when given the same set of characters and the same length.
Well, now I basically need the same but for combinations, in contrast to permutations as in my other question.
Can the algorithm above be modified in the same way? Meaning to create a function like
public function getCombinationByIndex($length, $index);
That will return one combination out of the thousand possible that is created with the algorithm without creating them beforehand?