title: unique permutations of variable length
body: <p>I need to get an array of unique permutations of any length:</p>
  
  <p>array of values: a, b, c, d, e, f, g, h, i, j, k, l, m (13 total)<br>
  expected result: a, b, c, ab, ac, bc, abc, ....<br>
  ab == ba (duplicate)<br>
  abc == acb == bca == bac == ... (duplicates)</p>
  
  <p>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.</p>
  
  <p>My current wild solution:</p>
  
  <pre><code>// 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 &lt;= 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 &lt; $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 &lt;= $len; $c++) {
    $p = getPermCount($letters, $c);
    echo $c." {".$p." perms} - ";
    for($i = 0; $i &lt; $p; $i++) {
      $r[] = getPerm($letters, $c, $i)." ";
      if ($b &gt; 4000000) {
          $r = array_flip($r); // &lt;= faster alternative to array_unique
          $r = array_flip($r); //    flipping values to keys automaticaly removes dupes
          $b = 0;
      } else {
          $b++;
      }
    }
  
    $r = array_flip($r); // &lt;= faster alternative to array_unique
    $r = array_flip($r); //    flipping values to keys automaticaly removes dupes
    echo count($r)." unique\n";
  }
  
  print_r($r);
  </code></pre>