【问题标题】:PHP permutation multiple same elementsPHP排列多个相同的元素
【发布时间】:2012-11-06 12:16:58
【问题描述】:

我需要一个返回所有可能组合的函数,

例如

chars = range('a', 'c');

  1. = a a a
  2. = a a b
  3. = a b a
  4. = a b b
  5. = a b c
  6. = a c b ... n. = c c c

(顺序无关紧要)

等等

我知道了

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        $return = array($perms);
    }  else {
        $return = array();
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
         list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             $return = array_merge($return, pc_permute($newitems, $newperms));
         }
    }
    return $return;
}

$p = pc_permute(array(0, 1, 2, 3));
var_dump($p);

来自Here

但我无法弄清楚如何机会/重写它以获得与多个相同元素的所有可能组合。

谢谢,穆哈默

【问题讨论】:

    标签: php permutation


    【解决方案1】:

    请使用此功能:

    <?php 
    $characters = range('a','c');
    
    
    function get_permutations(array $arr = array()){
        if(count($arr) == 1){
            return array_values($arr);
        }
    
        $return_array = array();
    
        foreach($arr as $key => $val){
            $temp_arr = $arr;
            unset($temp_arr[$key]);
            $temp = call_user_func(__FUNCTION__, $temp_arr);
            for($x = 0; $x < count($temp); $x++){
                $temp[$x] = $val.$temp[$x];
            }
            $return_array = array_merge($return_array, $temp);
        }
        return $return_array;
    }
    
    var_dump(get_permutations($characters));
    

    输出:

    array(6) {
      [0]=>
      string(3) "abc"
      [1]=>
      string(3) "acb"
      [2]=>
      string(3) "bac"
      [3]=>
      string(3) "bca"
      [4]=>
      string(3) "cab"
      [5]=>
      string(3) "cba"
    }
    

    编辑:

    <?php 
    $characters = range('a','h');
    
    
    function get_permutations(array $arr = array(), $max_length = NULL){
        if(count($arr) == 1 || ($max_length !== NULL && $max_length <= 1)){
            return array_values($arr);
        }
    
        $return_array = array();
    
        foreach($arr as $key => $val){
            $temp_arr = $arr;
            unset($temp_arr[$key]);
            $temp = call_user_func(__FUNCTION__, $temp_arr, $max_length !== NULL ? $max_length - 1 : NULL);
            for($x = 0; $x < count($temp); $x++){
                $temp[$x] = $val.$temp[$x];
            }
            $return_array = array_merge($return_array, $temp);
        }
        return $return_array;
    }
    
    var_dump(get_permutations($characters, 4));
    

    注意:注意使用a-z 范围会导致运行时间变长甚至导致内存不足错误,因此我使用小范围对其进行了测试:)

    【讨论】:

    • 谢谢,工作绝对完美!!如何修改此函数以获取 range('a','z');但具有预定义的字符串长度,例如5个字符?
    • @Mohammer : 对不起 l8 响应,传递另一个变量并设置值并将值测试为零,并在每次递归时减小值,在一段时间内检查编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    相关资源
    最近更新 更多