开发者

How can I get all unique combinations of a word's characters?

I understand how str_shuffle() or shuffle works but I don't know it in this case.

$word="tea";

I want to开发者_JAVA技巧 echo out all unique shuffling possibilities (tea, tae, eta, eat, ate, aet)


You need to produce all of the permutations of the string, either by iterating through the possibilities, or using a recursive method like this one below. Note that for a moderately sized array this will grow very large very quickly. For a word with unique characters, the number of possible permutations is n! where n is the length. For a six-letter word the array will have 720 entries! This method is not the most efficient, but depending on what you are trying to do, it should work ok.

(Source: 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;
}

Note that this somewhat naive implementation will not handle duplicate letters correctly (for example, 'seed', having two e`s). As indicated in the source above, you can use the following code to eliminate duplicates if the word contains multiple of the same letter:

$permutations = array_unique(permute($str));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜