Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何创建子集数组_Php_Arrays_Subset - Fatal编程技术网

Php 如何创建子集数组

Php 如何创建子集数组,php,arrays,subset,Php,Arrays,Subset,例如,给定一个数组: $array = array(1,2,3); 如何创建包含所有可能子集的数组: [1, 2, 3, [1,2], [1,3],[2,3]] 我认为这是一个很好的问题发现集合的子集有几种方法 我更喜欢使用二进制方法: 对于一组给定的n,有n^2个suset。您可以从0到2^n进行二进制计数,并将二进制数解释为相应的子集。请注意,这种方法需要一个具有足够数量的数字的二进制数来表示整个集合,因此我们需要填充二进制表示 更多阅读: 我的实施: $arr = array(1,2,

例如,给定一个数组:

$array = array(1,2,3);
如何创建包含所有可能子集的数组:

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

我认为这是一个很好的问题发现集合的子集有几种方法 我更喜欢使用二进制方法:

对于一组给定的
n
,有
n^2个
suset。您可以从0到2^n进行二进制计数,并将二进制数解释为相应的子集。请注意,这种方法需要一个具有足够数量的数字的二进制数来表示整个集合,因此我们需要填充二进制表示

更多阅读

我的实施

$arr = array(1,2,3);
$res = subsets($arr);

function subsets($arr,$sort = true,$include_empty = false,$include_full = false) {
   $length = count($arr);
   $res = array();
   if (!$length && $include_full) return $res;
   for ($i = 0; $i<pow(2, $length); $i++) {
       $set = array();
       $bin = str_split(str_pad(decbin($i), $length, "0", STR_PAD_LEFT));
       $binLen = count($bin);
       for ($j = 0; $j < $binLen; $j++)
           if ($bin[$j] === "1") $set[] = $arr[$j];
       $res[] = $set;
    }
    foreach($res as $k => $val)
       if (!count($val) && !$include_empty) unset($res[$k]);
       elseif (count($val) === $length && !$include_full) unset($res[$k]);
    function cmp($a, $b){ return (count($a) - count($b)); }
    if ($sort) usort($res, 'cmp');
    return $res;
}

//Output Results:
foreach ($res as $key => $data) {
   echo $key." -> [".(implode(',',$data))."]\r";
}
/*
0 -> [1]
1 -> [3]
2 -> [2]
3 -> [1,2]
4 -> [2,3]
5 -> [1,3]
*/
删除:

(2^n) + n*(2^n)
移除和排序(最坏情况):

假设我们有一个具有9个值的输入数组:

(2^9)*9 = 4608;

(2^9) + 9*(2^9) = 5120;

(2^9) + 9*(2^9) + 9^2 = 5201;
这是我知道的最快的方法

注意: 函数需要一个唯一的数组-您可以确保数组是唯一的:

$arr = array_unique ($arr);
(2^9)*9 = 4608;

(2^9) + 9*(2^9) = 5120;

(2^9) + 9*(2^9) + 9^2 = 5201;
$arr = array_unique ($arr);