2011-07-23 9 views

答えて

4

を、いずれかを反復して、すべてのユニークなシャッフルの可能性をエコーし​​たいです可能性、または以下のような再帰的な方法を使用しています。中程度のサイズの配列の場合、これは非常に迅速に非常に大きくなることに注意してください。一意の文字を持つ単語の場合、可能な置換の数はnです。ここで、nは長さです。 6文字の単語の場合、配列には720のエントリがあります!この方法は最も効率的ではありませんが、何をしようとしているかによってはうまくいくはずです。

(出典:http://cogo.wordpress.com/2008/01/08/string-permutation-in-php/)このやや素朴な実装が正しく重複文字を処理しないこと

function permute($str) { 
    /* If we only have a single character, return it */ 
    if (strlen($str) < 2) { 
     return array($str); 
    } 

    /* Initialize the return value */ 
    $permutations = array(); 

    /* Copy the string except for the first character */ 
    $tail = substr($str, 1); 

    /* Loop through the permutations of the substring created above */ 
    foreach (permute($tail) as $permutation) { 
     /* Get the length of the current permutation */ 
     $length = strlen($permutation); 

     /* Loop through the permutation and insert the first character of the original 
     string between the two parts and store it in the result array */ 
     for ($i = 0; $i <= $length; $i++) { 
      $permutations[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i); 
     } 
    } 

    /* Return the result */ 
    return $permutations; 
} 

注意(例えば、 'シード'、2 e`sを持ちます)。上記の情報源に示されているように、同じ文字の複数の単語が含まれている場合は、次のコードを使用して重複を排除できます。

$permutations = array_unique(permute($str)); 
関連する問題