2

我知道这个话题被讨论了很多,但我似乎找不到任何适合我需要的实现。

我有以下一组字符:

abcdefgh

我想获得所有可能的排列或组合(不重复),但在有限(可变)字符集上,这意味着如果我输入字符和数字2,结果应该看起来像

ab ba ac ca ad da ae ea af fa ag ga ah ha
bc cb bd db be eb bf fb bg gb bh hb
cd dc ce ec cf fc cg gc ch hc
de ed df fd dg gd dh hd
ef fe eg ge eh he
fg gf fh hf
gh hg

我希望你明白我的意思。我目前有一个实现,它给了我所有字符的排列,但我无法理解如何为这些排列实现有限的空间:

public function getPermutations($letters) {
    if (strlen($letters) < 2) {
        return array($letters);
    }

    $permutations = array();
    $tail = substr($letters, 1);

    foreach ($this->getPermutations($tail) as $permutation) {
        $length = strlen($permutation);

        for ($i = 0; $i <= $length; $i++) {
            $permutations[] = substr($permutation, 0, $i) . $letters[0] . substr($permutation, $i);
        }
    }

    return $permutations;
}
4

2 回答 2

4

如果一次只需要一个元素,则可以通过单独生成每个元素来节省内存。

如果我们想在您的预期输出集中生成一个随机字符串,我们可以使用这个算法:

Given a set of characters S, and a desired output length K:
  While the output has less than K characters:
    Pick a random number P between 1 and |S|.
    Append the P'th character to the output.
    Remove the P'th character from S.

其中|S|是 S 中的当前元素数。

我们实际上可以将这个选择序列编码为一个整数。一种方法是这样更改算法:

Given a set of characters S, and a desired output length K:
  Let I = 0.
  While the output has less than K characters:
    I = I * (|S| + 1).
    Pick a random number P between 1 and the number of elements in S.
    I = I + P.
    Append the P'th character to the output.
    Remove the P'th character from S.

运行此算法后,该值I将对这个特定的选择序列进行唯一编码。它基本上将其编码为混合基数;一个数字使用基数 N,下一个数字使用 N-1,依此类推,直到最后一个数字是基数 N-K+1(N 是输入中的字母数)。

当然,我们也可以再次解码,在 PHP 中,会是这样的:

// 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 = '';
  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;
}

(请注意,为简单起见,这个特定的解码算法并不完全对应于我之前描述的编码算法,但保持了给定$index映射到唯一结果的理想属性。)

要使用此代码,您将执行以下操作:

$letters = 'abcd';
echo '2 letters from 4:<br>';
for($i = 0; $i < getPermCount($letters, 2); $i++)
  echo getPerm($letters, 2, $i).'<br>';

echo '<br>3 letters from 4:<br>';
for($i = 0; $i < getPermCount($letters, 3); $i++)
  echo getPerm($letters, 3, $i).'<br>';
?>
于 2012-11-02T11:29:24.417 回答
2
$strings = get_perm( range('a', 'h'), 4 );

function get_perm( $a, $c, $step = 0, $ch = array(), $result = array() ){
    if( $c == 1 ){ //if we have last symbol in chain
        for( $k = 0; $k < count( $a ); $k++ ){
            if( @in_array( $k, $ch ) ) continue; // if $k exist in array we already have such symbol in string
            $tmp = '';

            foreach( $ch as $c ) $tmp .= $a[$c]; // concat chain of previous symbols
            $result[] = $tmp . $a[$k]; // and adding current + saving to our array to return
        }
    }else{
        for( $i = 0; $i < count( $a ); $i++ ){
            if( @in_array( $i, $ch ) ) continue;
            $ch[$step] = $i; // saving current symbol for 2 things: check if that this symbol don't duplicate later and to know what symbols and in what order need to be saved
            get_perm( $a, $c-1, $step+1, $ch, &$result ); 
            // recursion, 
            // decrementing amount of symbols left to create string, 
            // incrementing step to correctly save array or already used symbols, 
            // $ch - array of already used symbols, 
            // &$result - pointer to result array
        }
    }

    return $result;
}

注意

啊,有 6 个符号 = 数组中有 20k 个值
az 有 4 个符号 = 数组中有 358799 个值
所以 10 个符号的 az 肯定会死掉 =) 它需要太多的内存。
如果需要大量值,则需要尝试将输出保存到文件或数据库。或者将内存限制扩展到 php 但不确定这是否是最好的方法。

于 2012-11-01T11:01:39.587 回答