PHP递归以获取所有可能的字符串 [英] Php recursion to get all possibilities of strings
问题描述
这是我获得所有可能性的代码:
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迭代到2 count(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需要能够将2 count(array)作为整数进行计算,因此该值不得超过PHP_INT_MAX
.在64位PHP安装中,您的数组不能包含62个以上的元素,因为2 62 保持在PHP_INT_MAX
以下,而2 63 超出了该元素.
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屋!