Php recursion to get all possibilities of strings

后端 未结 6 1860
失恋的感觉
失恋的感觉 2020-11-27 07:22

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         


        
6条回答
  •  我在风中等你
    2020-11-27 08:23

    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.

    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.

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

提交回复
热议问题