【发布时间】:2011-10-11 11:20:56
【问题描述】:
我了解str_shuffle() 或 shuffle 的工作原理,但在这种情况下我不知道。
$word="tea";
我想呼应所有独特的洗牌可能性(tea、tae、eta、eat、ate、aet)
【问题讨论】:
我了解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`s)。如上面的来源所示,如果单词包含多个相同的字母,您可以使用以下代码来消除重复:
$permutations = array_unique(permute($str));
【讨论】: