Php递归获取字符串的所有可能性

iqjalb3h  于 2022-12-17  发布在  PHP
关注(0)|答案(6)|浏览(135)

下面是我的代码来获取所有可能性:

$seq[1] = 'd';
$seq[2] = 'f';
$seq[3] = 'w';
$seq[4] = 's';

for($i = 1; $i < 5; $i++)
{
    $s['length_1'][] = $seq[$i];
    $c1++;

    for($i2 = $i+1; $i2 < 5; $i2++)
    {
        $s['length_2'][] = $seq[$i].$seq[$i2]; 
        $last = $seq[$i].$seq[$i2]; 
        $c2++;

        for($i3 = $i2+1; $i3 < 5; $i3++)
        { 
            $s['length_3'][] = $last.$seq[$i3];
            $last = $last.$seq[$i3];    
            $c3++;

            for($i4 = $i3+1; $i4 < 5; $i4++)
            {
                $s['length_4'][] = $last.$seq[$i4];   
                $c4++;  
            }
        }
    }
}

for($i = 0; $i < $c1; $i++)
    echo $s['length_1'][$i].'<br>'; 

for($i = 0; $i < $c2; $i++)
    echo $s['length_2'][$i].'<br>';   

for($i = 0; $i < $c3; $i++)
    echo $s['length_3'][$i].'<br>';  

for($i = 0; $i < $c4; $i++)
    echo $s['length_4'][$i].'<br>';

但是如果我想添加更多,那么我将不得不添加更多的循环。那么,我怎么能用递归做到这一点呢?我尝试,我尝试,但我真的不能做到这一点。请帮助和后的例子尽可能简单。
谢谢你。

5cnsuln7

5cnsuln71#

这里有一个算法

function getCombinations($base,$n){

$baselen = count($base);
if($baselen == 0){
    return;
}
    if($n == 1){
        $return = array();
        foreach($base as $b){
            $return[] = array($b);
        }
        return $return;
    }else{
        //get one level lower combinations
        $oneLevelLower = getCombinations($base,$n-1);

        //for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add
        $newCombs = array();

        foreach($oneLevelLower as $oll){

            $lastEl = $oll[$n-2];
            $found = false;
            foreach($base as  $key => $b){
                if($b == $lastEl){
                    $found = true;
                    continue;
                    //last element found

                }
                if($found == true){
                        //add to combinations with last element
                        if($key < $baselen){

                            $tmp = $oll;
                            $newCombination = array_slice($tmp,0);
                            $newCombination[]=$b;
                            $newCombs[] = array_slice($newCombination,0);
                        }

                }
            }

        }

    }

    return $newCombs;

}

我知道这在任何方面都不是有效的,但是在小套中使用应该不是问题
第一基本参数是包含在生成组合时要考虑的元素的数组。
为了简化使用和输出:

var_dump(getCombinations(array("a","b","c","d"),2));

输出为

array
  0 => 
    array
      0 => string 'a' (length=1)
      1 => string 'b' (length=1)
  1 => 
    array
      0 => string 'a' (length=1)
      1 => string 'c' (length=1)
  2 => 
    array
      0 => string 'a' (length=1)
      1 => string 'd' (length=1)
  3 => 
    array
      0 => string 'b' (length=1)
      1 => string 'c' (length=1)
  4 => 
    array
      0 => string 'b' (length=1)
      1 => string 'd' (length=1)
  5 => 
    array
      0 => string 'c' (length=1)
      1 => string 'd' (length=1)

要列出一个数组的所有子集,使用此组合算法只需执行

$base =array("a","b","c","d");

for($i = 1; $i<=4 ;$i++){
    $comb = getCombinations($base,$i);

    foreach($comb as $c){
        echo implode(",",$c)."<br />";
    }

}

输出为

a
b
c
d
a,b
a,c
a,d
b,c
b,d
c,d
a,b,c
a,b,d
a,c,d
b,c,d
a,b,c,d
rn0zuynd

rn0zuynd2#

下面是一个简单的算法:从1迭代到2count(array)-1。在每次迭代中,如果循环计数器的二进制表示中的第j位等于1,则在组合中包含第j个元素。
由于PHP需要能够将2count(array)作为整数计算,因此不能超过PHP_INT_MAX。在64位PHP安装中,数组不能超过62个元素,因为262小于PHP_INT_MAX,而263大于PHP_INT_MAX
EDIT:计算所有可能的组合,而不是排列(例如,'abc' = 'cba')。它是通过用二进制表示原始数组,然后从0“向上计数”到整个数组的二进制表示来实现的,有效地构建了一个包含所有可能的唯一组合的列表。

$a = array('a', 'b', 'c', 'd');

$len  = count($a);
$list = array();

for($i = 1; $i < (1 << $len); $i++) {
    $c = '';
    for($j = 0; $j < $len; $j++)
        if($i & (1 << $j))
            $c .= $a[$j];
    $list[] = $c;
}

print_r($list);
bvjveswy

bvjveswy3#

这就是:

<?php
function combinations($text,$space)
{
    // $text is a variable which will contain all the characters/words of which  we want to make all the possible combinations
    // Let's make an array which will contain all the characters
    $characters=explode(",", $text);
    $x=count($characters);

    $comb = fact($x);

    // In this loop we will be creating all the possible combinations of the  positions that are there in the array $characters

    for ($y=1; $y<= $comb; $y++)
    {
        $ken = $y-1;
        $f = 1;
        $a = array();
        for($iaz=1; $iaz<=$x; $iaz++)
            {
                $a[$iaz] = $iaz;
                $f = $f*$iaz;
            }
        for($iaz=1; $iaz<=$x-1; $iaz++)
            {
                $f = $f/($x+1-$iaz);
                $selnum = $iaz+$ken/$f;
                $temp = $a[$selnum];
                for($jin=$selnum; $jin>=$iaz+1; $jin--)
                    {
                        $a[$jin] = $a[$jin-1];
                    }
                $a[$iaz] = $temp;
                $ken = $ken%$f;
            }
        $t=1;

           // Let’s start creating a word combination: we have all the  necessary positions
        $newtext="";

        // Here is the while loop that creates the word combination
        while ($t<=$x)
            {
                $newtext.=$characters[$a[$t]-1]."$space";
                $t++;
            }
        $combinations[] =  $newtext ;
    }

        return $combinations;

}

function fact($a){
if ($a==0) return 1;
else return $fact = $a * fact($a-1);
}

$a = combinations("d,f,w,s","");
    foreach ($a as $v) {
            echo "$v"."\n";
    }

?>

输出:

dfws
dfsw
dwfs
dwsf
dsfw
dswf
fdws
fdsw
fwds
fwsd
fsdw
fswd
wdfs
wdsf
wfds
wfsd
wsdf
wsfd
sdfw
sdwf
sfdw
sfwd
swdf
swfd

同样,read this;

44u64gxh

44u64gxh4#

您可以执行以下操作:

function combinations($arr) {
    $combinations = array_fill(0, count($arr)+1, array());
    $combinations[0] = array('');
    for ($i = 0, $n = count($arr); $i < $n; ++$i) {
        for ($l = $n-$i; $l > 0; --$l) {
            $combinations[$l][] = implode('', array_slice($arr, $i, $l));
        }
    }
    return $combinations;
}

下面是一个例子:

$arr = array('d', 'f', 'w', 's');
var_dump(combinations($arr));

这将生成以下数组:

array(
    array(''),                 // length=0
    array('d', 'f', 'w', 's'), // length=1
    array('df', 'fw', 'ws'),   // length=2
    array('dfw', 'fws'),       // length=3
    array('dfws')              // length=4
)

简要说明:
对于每个0 ≤ ini,得到‍‍‍所有可能长度为0〈ln - i 的子数组 arr [ii+ l]。

3j86kqsm

3j86kqsm5#

下面是打印所有可能的字符组合的函数:

function printCombinations($var, $begin = 0, $preText = "") {
    for($i = $begin; $i < count($var); $i++) {
        echo $preText . $var[$i] . "\n";
        if(($i+1) < count($var))
            printCombinations($var, $i+1, $preText . $var[$i]);
    }
}

printCombinations(array('a','b','c','d','e'));
tsm1rwdh

tsm1rwdh6#

下面是在codeigniter/php中执行此操作另一种方法。

`function recursiveCombinations($var,$n = '') {
    $len = count($var);
    if ($n == 0){
        return array(array());
    }
   $arr = [];
   for ($i = 0;$i<$len;$i++){
       $m = $var[$i];
       $remLst = array_slice($var, $i + 1); 
       $remainlst_combo = $this->recursiveCombinations($remLst, $n-1);
       foreach ($remainlst_combo as $key => $val){
       array_push($arr,array_merge(array($m),$val));
       }
}
return $arr;
}

    $arr = ['a','b','c','d','e','f','g','h','i','j','l','m','n','o','p'];
    $n = $this->recursiveCombinations($arr,5);`

相关问题