PHP Find All (somewhat) Unique Combinations of an Array

后端 未结 6 2206
独厮守ぢ
独厮守ぢ 2020-12-03 12:02

I\'ve been looking at PHP array permutation / combination questions all day.. and still can\'t figure it out :/

If I have an array like:

20 //key bei         


        
6条回答
  •  眼角桃花
    2020-12-03 12:30

    Had the same problem and found a different and bitwise, faster solution:

    function bitprint($u) {
        $s = array();
        for ($n=0; $u; $n++, $u >>= 1){
            if ($u&1){
                $s [] = $n;
            }
        }
        return $s;
    }
    function bitcount($u) {
        for ($n=0; $u; $n++, $u = $u&($u-1));
        return $n;
    }
    function comb($c,$n) {
        $s = array();
        for ($u=0; $u<1<<$n; $u++){
            if (bitcount($u) == $c){
                $s [] = bitprint($u);
            }
        }
        return $s;
    }
    

    This one generates all size m combinations of the integers from 0 to n-1, so for example m = 2, n = 3 and calling comb(2, 3) will produce:

    0 1
    0 2
    1 2
    

    It gives you index positions, so it's easy to point to array elements by index.

    Edit: Fails with input comb(30, 5). Have no idea why, anyone any idea?

提交回复
热议问题