在PHP中查找数组的子集 [英] Finding the subsets of an array in PHP

查看:243
本文介绍了在PHP中查找数组的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性关系模式(A B C D)。
我也有一组功能依赖关系。



现在我需要确定R属性的所有可能子集的关闭。那就是我被困的地方我需要学习如何在PHP中找到子集(非重复)。



我的数组是这样存储的。

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

所以我的子集应该是

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

不要太大,但由于某种原因,我无法让我的头脑。

解决方案

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



可以找到一个例子 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 <$ count; $ 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; 
} 

这篇关于在PHP中查找数组的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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