Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

php - Combinations of X elements into 1, 2, 3, 4, ... X sub-sub-arrays

I have an array that looks like this: [0, 1, 2, 3, 4, 5, ...]

I need a function that will give me an array like this:

[
[[0, 1, 2, 3, 4, 5]],  
[[0, 1, 2, 3, 4], [ 5 ]], 
[[0, 1, 2, 3], [ 4, 5 ]], 
[[0, 1, 2], [ 3, 4, 5 ]], 
...
[[0, 1, 2], [ 3, 4 ], [ 5 ]],
...
[[ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ]]
]

Of course this output is only for 6 elements.
If you look at the 2nd, 3rd and 4th line of the output array, it's some sort of combination into 2 sub-arrays.
If you look at the 6th line of the output array, it becomes into 3 sub-arrays.
In the last line every element should be alone in its own sub-array.

I saw the examples on this page and I tried the functions but mine is a little different because the order of the elements need to be respected. This means that regardless of where the brackets are, you should see 1 2 3 4 5 6 on each line.

Also, the functions in the previously mentioned page will give me an array including all the sub-arrays:
[[x,x],[x],[x],[xxx]] I can't use this.

What I need is this format:

[  
[ [ 1 , 2 , 3 ] ] ,  
[ [ 1 , 2 ] , [ 3 ] ] ,  
[ [ 1 ] , [ 2 , 3 ] ] ,  
[ [ 1 ] , [ 2 ] , [ 3 ] ]  
]

I am a beginner, please someone give me a hint on how to do this!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've just developed a very special way to achieve what you're looking for (traversing a binary tree using binary labels! I don't know if it already exists!!) It's extremely fast and doesn't use recursion :)

<?php
function getSpecialSubsets($in) {
    $in = array_reverse($in);
    $n = count($in);

    $out = array();
    // for every possible route
    for($i = 0; $i<pow(2, $n-1); $i++) {
        $out[$i] = array(array());

        // for every value in the input array
        for($j=$n-1; $j>=0; $j--) {
            $val = $in[$j];
            if(($i >> $j) & 1)
                $out[$i][] = array($val);
            else $out[$i][count($out[$i])-1][] = $val;
        }
    }

    return $out;
}

$subsets = getSpecialSubsets([1, 2, 3, 4]);

// for demonstration purposes only!!
echo "<pre>";
echo preg_replace('~]],~', "]],
", json_encode($subsets));
echo "</pre>";
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...