且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中查找数组的子集

更新时间:2022-10-24 18:30:36

$属性?这就是你的问题所在。



可以找到一个例子 here (引用为完整性)

 <?php 
/ **
*返回一维数组的幂组,即二维数组。
* [a,b,c] - > [a],[b],[c],[a,b],[a,c],[b,c],[a,b,c]]
* /
函数powerSet($ in,$ minLength = 1){
$ count = count($ in);
$ members = pow(2,$ count);
$ return = array();
($ i = 0; $ i< $ members; $ i ++){
$ b = sprintf(%0。$ count。b,$ i);
$ out = array();
($ j = 0; $ j if($ b {$ j} =='1')$ out [] = $ in [$ j ]。
}
if(count($ out)> = $ minLength){
$ return [] = $ out;
}
}
return $ return;
}


I have a Relational Schema with attributes (A B C D). I have a set of Functional Dependencies with me too.

Now I need to determine the closure for all the possible subsets of R's attributes. That's where I am stuck. I need to learn how to find subsets (non-repeating) in PHP.

My Array is stored like this.

$ATTRIBUTES = ('A', 'B', 'C', 'D').

so my subsets should be

$SUBSET = ('A', 'B', 'C', 'D', 'AB', 'AC', AD', 'BC', 'BD', 'CD', 'ABC', 'ABD', 'BCD', 'ABCD')

The code shouldn't be something big but for some reason I can't get my head around it.

You wish for the power set of $attributes? That is what your question implies.

An example can be found here (quoted for completeness)

<?php 
/** 
* Returns the power set of a one dimensional array, a 2-D array. 
* [a,b,c] -> [ [a], [b], [c], [a, b], [a, c], [b, c], [a, b, c] ]
*/ 
function powerSet($in,$minLength = 1) { 
   $count = count($in); 
   $members = pow(2,$count); 
   $return = array(); 
   for ($i = 0; $i < $members; $i++) { 
      $b = sprintf("%0".$count."b",$i); 
      $out = array(); 
      for ($j = 0; $j < $count; $j++) { 
         if ($b{$j} == '1') $out[] = $in[$j]; 
      } 
      if (count($out) >= $minLength) { 
         $return[] = $out; 
      } 
   } 
   return $return; 
}