php - 如何获得单词字符的所有唯一组合?

标签 php arrays unique shuffle

我了解 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/

相关文章:

python - 对矩阵中的第一列和第二个列表执行 "AND"操作

c - 了解由于 getchar 而导致的 c 循环

php - 通过迁移从其他列创建昵称,laravel 8

javascript - 将一个数组映射到具有负索引偏移量的第二个数组

php - MySql 连接查询左连接

java - 查找非重复元素。代码不打印任何内容

mysql - 具有大小问题的独特字段

java - 从数组到数组创建新对象

php - SQL - 验证现有数据

php - 我应该如何获取 Drupal 7 自定义节点的特定字段中包含的值?