Php递归获取字符串的所有可能性 [英] Php recursion to get all possibilities of strings

查看:22
本文介绍了Php递归获取字符串的所有可能性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我获得所有可能性的代码:

Here is my code to get all possibilities:

$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>';    

但是如果我想添加更多,那么我将不得不再添加一个循环.那么,我怎样才能用递归来做到这一点呢?我尝试,我尝试,但我真的做不到.请帮助并尽可能简单地发布示例.

But if I want to add more, then I will have to add one more loop. So, how can I do it with recursion? I try, I try, but I really can't do it. Please help and post example as simple as possible.

谢谢.

推荐答案

这是一个简单的算法.从 1 迭代到 2count(array)-1.在每次迭代中,如果循环计数器的二进制表示中的第 j 位等于 1,则在组合中包含第 j 个元素.

Here's a simple algo. Iterate from 1 to 2count(array)-1. On each iteration, if j-th bit in a binary representation of the loop counter is equal to 1, include j-th element in a combination.

由于 PHP 需要能够将 2count(array) 计算为整数,因此这可能永远不会超过 PHP_INT_MAX.在 64 位 PHP 安装中,您的数组不能超过 62 个元素,因为 262 低于 PHP_INT_MAX 而 263 超过它.

As PHP needs to be able to calculate 2count(array) as an integer, this may never exceed PHP_INT_MAX. On a 64-bit PHP installation your array cannot have more than 62 elements, as 262 stays below PHP_INT_MAX while 263 exceeds it.

这会计算所有可能的组合,而不是排列(即,'abc' = 'cba').它通过以二进制表示原始数组并从 0 到整个数组的二进制表示向上计数",从而有效地构建每个可能的唯一组合的列表.

This computes all possible combinations, not permutations (ie, 'abc' = 'cba'). It does so by representing the original array in binary and "counting up" from 0 to the binary representation of the full array, effectively building a list of every possible unique combination.

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

这篇关于Php递归获取字符串的所有可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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