0

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);
hpet
  • 299
  • 2
  • 14

1 Answers1

0

I took a crack at it:

function get_perms(chars) {
    var perms = [ chars[0] ];
    for (var i = 1; i < chars.length; i += 1) {
        len = perms.length;
        for (var j = 0; j < len; j += 1) {
            perms.push(perms[j] + chars[i]);
        }
    }
    return perms;
}

var chars = [ "a", "b", "c", "d", "e" ], perms = [];
for (var i = 0; i < chars.length; i += 1) {
    perms = perms.concat(get_perms(chars.slice(i)));
}
console.log(perms);

The outline is:

Start with the full set [ "a", "b", "c", "d", "e", .. ]

Generate all ascending permutations, a, ab, ac, abc, etc. but never acb. I do this by starting with ["a"] now add "b" to all of those and merge to get: ["a", "ab"], now add "c" to all of those and merge: ["a", "ab", "ac", "abc"] etc.

The do all this again for the set [ "b", "c", "d", "e", .. ] and then for [ "c", "d", "e", .. ] etc.

This should give you all permutations without duplicates.


Sample output (for [ "a", "b", "c", "d", "e" ]):

["a", "ab", "ac", "abc", "ad", "abd", "acd", "abcd", "ae", "abe", "ace", "abce", "ade", "abde", "acde", "abcde",
 "b", "bc", "bd", "bcd", "be", "bce", "bde", "bcde",
 "c", "cd", "ce", "cde",
 "d", "de",
 "e"]

A full set of 13 characters took less than 1 second to generate on my machine so I'm not going to bother to measure. Also, I realize I did this is JavaScript instead of PHP, it shouldn't be too hard to convert.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • that's the new PHP6 syntax ? :-) – Amine Matmati May 16 '14 at 14:59
  • No, it's JavaScript :P - should be easy enough to convert to PHP. `array_slice`, `array_merge` and `array_push`. `count()` instead of `.length`. – Halcyon May 16 '14 at 14:59
  • 1
    Thank you very much :) In a mean time I also found out a bit more mathematical way of doing it - for those interested! ...and that this is actualy called combinations not permutations :) http://www.mathsisfun.com/combinatorics/combinations-permutations.html – hpet May 19 '14 at 08:49