如何在没有顺序重复的情况下获得PHP中的所有排列? [英] How can I get all permutations in PHP without sequential duplicates?

查看:98
本文介绍了如何在没有顺序重复的情况下获得PHP中的所有排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经以多种形式提出了这个问题.我想在PHP中使用数组,并获取所有可能的组合/排列.我想要整个集合以及部分集合的排列.

This question has been asked in many forms. I want to take an array in PHP and get all possible combinations / permutations. I want both permutations of the whole set as well as a partial set.

我对这个问题的看法是,我要如何从结果项中删除顺序重复项.通过使用" PHP接受所有组合并添加一个函数,我接近了我想要的东西:

My twist on this question is asking how can I remove sequential duplicates from within the result items. I got close to what I wanted by using " PHP take all combinations " and adding a function:

$words = array('a','b','c');
function permutations($arr,$n)
{
    $res = array();
    foreach ($arr as $w)
    {
        if ($n==1) $res[] = $w;
        else
        {
            $perms = permutations($arr,$n-1);
            foreach ($perms as $p)
            {
                $res[] = $w." ".$p;
            } 
        }
    }
    return $res;
}

function get_all_permutations($words=array())
{
    $r = array();
    for($i=sizeof($words);$i>0;$i--)
    {
        $r = array_merge(permutations($words,$i),$r);
    }
    return $r;
}

$permutations = get_all_permutations($words);
print_r($permutations);

这将输出:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => a a
    [4] => a b
    [5] => a c
    [6] => b a
    [7] => b b
    [8] => b c
    [9] => c a
    [10] => c b
    [11] => c c
    [12] => a a a
    [13] => a a b
    [14] => a a c
    [15] => a b a
    [16] => a b b
    [17] => a b c
    [18] => a c a
    [19] => a c b
    [20] => a c c
    [21] => b a a
    [22] => b a b
    [23] => b a c
    [24] => b b a
    [25] => b b b
    [26] => b b c
    [27] => b c a
    [28] => b c b
    [29] => b c c
    [30] => c a a
    [31] => c a b
    [32] => c a c
    [33] => c b a
    [34] => c b b
    [35] => c b c
    [36] => c c a
    [37] => c c b
    [38] => c c c
)

我知道一旦生成了集合,我就可以查看输出,但是有可能在生成过程中删除顺序重复项吗?

I know I could look through the output once the set has been generated, but is it possible to remove the sequential duplicates during generation?

应转换/删除的示例:

  • c c c将与c
  • 相同
  • c c bc b
  • 相同
  • c c c c c也将与c相同(如果集合更大)
  • c c c would be the same as c
  • c c b would be the same as c b
  • c c c c c would also be the same as c (if the set was larger)

注意:

  • 我对递归并不满意,但是可能有一种花哨的方法可以将我拥有的两个功能组合为一个.
  • 现在输出集是字符串,但是我不介意它们是否是数组(如果这样会使事情变得更容易)

推荐答案

您可以将排列数组作为引用(带有&"号)作为permutations()的第三个参数,并在添加值之前运行in_array()检查.但是,这比在get_all_permutation()末尾删除重复项的性能要差得多.

You could pass the permutations array as a reference (with a proceeding ampersand) in as a third parameter of permutations() and run a in_array() check before adding a value. However this would be far less performant than removing duplicates at the end of get_all_permutation()

这篇关于如何在没有顺序重复的情况下获得PHP中的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆