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

我的未来我决定 提交于 2019-12-22 10:17:02

问题


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

$word="tea";

I want to echo out all unique shuffling possibilities (tea, tae, eta, eat, ate, aet)


回答1:


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));


来源:https://stackoverflow.com/questions/6797578/how-can-i-get-all-unique-combinations-of-a-words-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!