I need to get an array of unique permutations of any length:
array of values: a, b, c, d, e, f, g, h, i, j, k, l, m (13 total)
expected result: a, b, c, ab, ac, bc, abc, ....
ab == ba (duplicate)
abc == acb == bca == bac == ... (duplicates)
What I have so far is kind of a brute force attack at it, but with 13 elements this is kind of optimistic. I need something smarter, unfortunately something beyond my math capabilities.
My current wild solution:
// Returns the total number of $count-length strings generatable from $letters.
function getPermCount($letters, $count) {
$result = 1;
// k characters from a set of n has n!/(n-k)! possible combinations
for($i = strlen($letters) - $count + 1; $i <= strlen($letters); $i++) {
$result *= $i;
}
return $result;
}
// Decodes $index to a $count-length string from $letters, no repeat chars.
function getPerm($letters, $count, $index) {
$result = array();
for($i = 0; $i < $count; $i++) {
$pos = $index % strlen($letters);
$result[] = $letters[$pos];
$index = ($index-$pos)/strlen($letters);
$letters = substr($letters, 0, $pos) . substr($letters, $pos+1);
}
sort($result); // to be able and remove dupes later
return implode("", $result);
}
$r = array();
$letters = 'abcdefghijklm';
$len = strlen($letters);
$b = 0;
for ($c = 1; $c <= $len; $c++) {
$p = getPermCount($letters, $c);
echo $c." {".$p." perms} - ";
for($i = 0; $i < $p; $i++) {
$r[] = getPerm($letters, $c, $i)." ";
if ($b > 4000000) {
$r = array_flip($r); // <= faster alternative to array_unique
$r = array_flip($r); // flipping values to keys automaticaly removes dupes
$b = 0;
} else {
$b++;
}
}
$r = array_flip($r); // <= faster alternative to array_unique
$r = array_flip($r); // flipping values to keys automaticaly removes dupes
echo count($r)." unique\n";
}
print_r($r);