我了解 str_shuffle()
或 shuffle 的工作原理,但我不知道在这种情况下。
$word="tea";
我想回显所有独特的洗牌可能性(tea、tae、eta、eat、ate、aet)
最佳答案
您需要生成字符串的所有排列,可以通过遍历各种可能性,也可以使用如下所示的递归方法。请注意,对于中等大小的数组,它会很快变得非常大。对于具有唯一字符的单词,可能的排列数为 n!其中 n 是长度。对于一个六个字母的单词,数组将有 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;
}
请注意,这种有点幼稚的实现方式无法正确处理重复的字母(例如,“seed”有两个 e`)。如上面的源代码所示,如果单词包含多个相同的字母,您可以使用以下代码消除重复项:
$permutations = array_unique(permute($str));
关于php - 如何获得单词字符的所有唯一组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6797578/