2

可能なすべての組み合わせを返す関数が必要です。

例えば

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

  1. = aaa
  2. = aab
  3. =aba
  4. = abb
  5. = abc
  6. = acb...n。= ccc

(順序は関係ありません)

等々

私はこれを得た

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);

ここから

しかし、私はこれを偶然/書き直して、複数の同じ要素とのすべての可能な組み合わせを取得する方法を理解できませんでした。

ありがとう、モハマー

4

1 に答える 1

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。狭い範囲でテストしました:)

于 2012-11-06T12:48:30.467 に答える