X元素组合成1,2,3,4,... X个子子数组 [英] Combinations of X elements into 1, 2, 3, 4, ... X sub-sub-arrays

查看:126
本文介绍了X元素组合成1,2,3,4,... X个子子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数组:[0,1,2,3,4,5,... ...

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 ]]
]

当然,此输出仅包含6个元素.
如果查看输出数组的第二行,第三行和第四行,这是组合成2个子数组的某种形式.
如果查看输出数组的第6行,它将变成3个子数组.
在最后一行中,每个元素应在其自己的子数组中单独存在.

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.

我在此页面上看到了这些示例,我尝试了这些功能,但是我的功能有所不同,因为需要尊重元素的顺序.这意味着无论括号在哪里, 您应该在每行上看到1 2 3 4 5 6.

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.

此外,前面提到的页面中的函数将为我提供一个包含所有子数组的数组:
[[x,x],[x],[x],[xxx]]我不能使用它.

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.

我需要的是这种格式:

[  
[ [ 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!

推荐答案

我刚刚开发了一种非常特殊的方法来实现您想要的功能(使用二进制标签遍历二叉树!我不知道它是否已经存在!)它非常快,并且不使用递归:)

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('~\]\],~', "]],\n", json_encode($subsets));
echo "</pre>";
?>

这篇关于X元素组合成1,2,3,4,... X个子子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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