I've recently learnt about CNS and FNS, and since they look so elegant to me, I decided to try and implement methods to generate combinations and permutations using those techniques. I finished my method to convert from n choose k combinations to a CSN rank and vice-versa but I'm banging my head against the wall trying to do the same with n choose k (unique) permutations.
Thanks to @Joshua I got the unranking (FNS to permutation) method working:
function Pr_Unrank($n, $k, $rank) { // rank starts at 1
if ($n >= $k) {
if (($rank > 0) && ($rank <= Pr($n, $k))) {
$rank--;
$result = array();
$factoriadic = array();
for ($i = 1; $i <= ($n - $k); ++$i) {
$rank *= $i;
}
for ($j = 1; $j <= $n; ++$j) {
$factoriadic[$n - $j] = ($rank % $j) + 1; $rank /= $j;
}
for ($i = $n - 1; $i >= 0; --$i) {
$result[$i] = $factoriadic[$i];
for ($j = $i + 1; $j < $n; ++$j) {
if ($result[$j] >= $result[$i]) {
++$result[$j];
}
}
}
return array_reverse(array_slice($result, 0 - $k));
}
}
return false;
}
This is my current attempt at a ranking (permutation to FNS) method:
function Pr_Rank($n, $k, $permutation) {
if ($n >= $k) {
$result = range(1, $n);
$factoriadic = array();
foreach ($permutation as $key => $value) {
$factoriadic[$k - $key - 1] = array_search($value, $result);
array_splice($result, $factoriadic[$k - $key - 1], 1);
}
$result = 1;
foreach (array_filter($factoriadic) as $key => $value) {
$result += F($key) * $value;
}
return $result;
}
return false;
}
And these are the helper functions I'm using:
function F($n) { // Factorial
return array_product(range($n, 1));
}
function Pr($n, $k) { // Permutations (without Repetitions)
return array_product(range($n - $k + 1, $n));
}
The problem is, the Pr_Rank()
method only returns the correct rank when n = k
(demo):
var_dump(Pr_Rank(5, 2, Pr_Unrank(5, 2, 10))); // 3, should be 10
var_dump(Pr_Rank(5, 3, Pr_Unrank(5, 3, 10))); // 4, should be 10
var_dump(Pr_Rank(5, 5, Pr_Unrank(5, 5, 10))); // 10, it's correct
I guided myself using the Wikipedia article I linked above and this MSDN article, I know neither of them contemplate k-sized subsets, but I'm completely in the dark what such logic would look like...
I also tried Googling and searching existing questions / answers but nothing relevant has come up yet.
See Question&Answers more detail:
os