我怎样才能得到一个字的字符的所有唯一组合? [英] How can I get all unique combinations of a word's characters?
问题描述
我知道如何 str_shuffle()
或洗牌的作品,但我不知道在这种情况下。
I understand how str_shuffle()
or shuffle works but I don't know it in this case.
$word="tea";
我想呼应了所有独特的洗牌可能性(茶,TAE,ETA,吃,吃,AET)
I want to echo out all unique shuffling possibilities (tea, tae, eta, eat, ate, aet)
推荐答案
您需要制作的所有字符串的排列,方法是通过迭代的可能性,或使用类似下面这一个递归方法。请注意,对于一个中等大小的数组,这将变得非常大非常快。对于具有独特字符的字,可能的排列的数量是n!其中n是长度。对于六个字母组成的单词数组将有720项!这种方法是不是最有效的,但是这取决于你正在尝试做的,它应该工作正常。
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.
(来源:的http:// cogo.word press.com / 2008/01/08 /串置换,在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;
}
请注意,这有点幼稚实施将不能正确处理重复字母(例如,种子,具有两个e`s)。如上文源指出,你可以使用下面的code。如果字包含相同字母的倍数,以消除重复:
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));
这篇关于我怎样才能得到一个字的字符的所有唯一组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!