在PHP中查找数组的子集

dtx*_*dtx 12 php arrays dependencies functional-programming subset

我有一个带属性的关系模式(ABCD).我也有一套功能依赖.

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

我的数组存储方式如下.

$ATTRIBUTES = ('A', 'B', 'C', 'D').
Run Code Online (Sandbox Code Playgroud)

所以我的子集应该是

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

代码不应该是大的东西,但由于某种原因,我无法理解它.

fbs*_*stj 23

你想要的功率集$attributes?这就是你的问题所暗示的.

这里可以找到一个例子(引用完整性)

<?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; 
} 
Run Code Online (Sandbox Code Playgroud)

  • 删除 `$b=sprintf(...)`,使用 `$i&gt;&gt;$j&amp;1` 而不是 `$b{$j} == '1'` - 更短更快。 (2认同)

Yad*_*ada 15

使用php array_merge我们可以有一个很好的短powerSet函数

function powerSet($array) {
    // add the empty set
    $results = array(array());

    foreach ($array as $element) {
        foreach ($results as $combination) {
            $results[] = array_merge(array($element), $combination);
        }
    }

    return $results;
}
Run Code Online (Sandbox Code Playgroud)