Actually this code working, but if input contain same char the result have a duplicate. This code i found here, but i cant find the solution to remove duplicate result when i try it self.
Here's the PHP code with an example
function getPermCount($letters, $count)
{
$result = 1;
for($i = strlen($letters) - $count + 1; $i <= strlen($letters); $i++) {
$result *= $i;
}
return $result;
}
function getPerm($letters, $count, $index)
{
$result = '';
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);
}
return $result;
For the example
$letters = 'abcc';
$cek = 2;
for($i = 0; $i < getPermCount($letters, $cek); $i++) {
$gege = getPerm($letters, $cek, $i).",";
echo $gege;
}
result
ab,ba,ca,ca,ac,bc,cb,cb,ac,bc,cc,cc,
I want the duplicate result removed, exactly like this
ab,ba,ca,ac,bc,cb,cc,
You can pass your result to an array and then remove the duplicated ones and pass back to string.
First you use explode() on your string to create an array using the , as separator:
$array = explode(",", $gege)
Then you can use array_unique() to remove duplicated values from the array:
$array_unique = array_unique($array);
When you have the array with unique values you just need to transform it back to string, you can use implode() and indicate , as a separator again for it:
$unique_string = implode("," $array_unique);
Fast example:
$gege = "ab,ba,ca,ca,ac,bc,cb,cb,ac,bc,cc,cc,";
echo implode(",",array_unique(explode(",", $gege)));
You can create a function to do it:
function stringUnique($string, $separator){
return implode($separator,array_unique(explode($separator, $string)));
}
Then after your permutation you can just run the function like this:
$gege = "";
for($i = 0; $i < getPermCount($letters, $cek); $i++) {
$gege .= getPerm($letters, $cek, $i).",";
}
echo stringUnique($gege, ",");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With