4

对不起标题,因为它看起来像大多数其他关于组合数组的问题,但我不知道如何更具体地写它。

我需要一个 PHP 函数,它将一个数组的条目(从 1 到任意的动态大小)组合成每个可能组合的字符串。

这是一个包含 4 个条目的示例:

$input = array('e1','e2','e3','e4);

这应该是结果:

$result = array(
    0 => 'e1',
    1 => 'e1-e2',
    2 => 'e1-e2-e3',
    3 => 'e1-e2-e3-e4',
    4 => 'e1-e2-e4',
    5 => 'e1-e3',
    6 => 'e1-e3-e4',
    7 => 'e1-e4'
    8 => 'e2',
    9 => 'e2-e3',
   10 => 'e2-e3-e4',
   11 => 'e2-e4',
   12 => 'e3',
   13 => 'e3-e4',
   14 => 'e4'
);

输入数组的排序是相关的,因为它会影响输出。如您所见,应该有一个结果 like e1-e2but no e2-e1

看起来真的很复杂,因为输入数组可以有任意数量的条目。我什至不知道是否有描述这种情况的数学结构或名称。

以前有人做过吗?

4

3 回答 3

2

您是说数组中可能有任意数量的条目,所以我假设您没有手动插入数据,并且会有一些源代码或代码输入数据。你能描述一下吗?根据您的要求直接存储它可能比拥有一个数组然后根据您的要求更改它更容易

这可能会有所帮助在 PHP 中查找数组的子集

于 2017-12-03T09:15:30.913 回答
0

我已经设法将一个代码组合在一起,该代码可以从您拥有的输入中创建您想要的输出。
我想我已经理解了每个项目何时以及为什么看起来像它的方式的逻辑。但我不确定,所以在现场使用之前要仔细测试。

我很难解释代码,因为它真的是一个障碍。

但是我使用 array_slice 来获取字符串中需要的值,并 implode 来添加-值之间的值。

$in = array('e1','e2','e3','e4');

//$new =[];
$count = count($in);
Foreach($in as $key => $val){
    $new[] = $val; // add first value

    // loop through in to greate the long incrementing string
    For($i=$key; $i<=$count-$key;$i++){
        if($key != 0){
             $new[] = implode("-",array_slice($in,$key,$i));
        }else{
            if($i - $key>1) $new[] = implode("-",array_slice($in,$key,$i));
        }
    }

    // all but second to last except if iteration has come to far
    if($count-2-$key >1) $new[] = Implode("-",Array_slice($in,$key,$count-2)). "-". $in[$count-1];

    // $key (skip one) next one. except if iteration has come to far
    If($count-2-$key >1) $new[] = $in[$key] . "-" . $in[$key+2];

    // $key (skip one) rest of array except if iteration has come to far
    if($count-2-$key > 1) $new[] = $in[$key] ."-". Implode("-",Array_slice($in,$key+2));

    // $key and last item, except if iteration has come to far
    if($count-1 - $key >1) $new[] = $in[$key] ."-". $in[$count-1];

}


$new = array_unique($new); // remove any duplicates that may have been created

https://3v4l.org/uEfh6

于 2017-12-03T12:08:39.197 回答
0

这是在 PHP 中查找数组的子集的修改版本

function powerSet($in,$minLength = 1) { 
    $count = count($in); 
    $keys = array_keys($in);
    $members = pow(2,$count); 
    $combinations = 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[] = $keys[$j]; 
          }
       } 
       if (count($out) >= $minLength) { 
          $combinations[] = $out; 
       } 
    } 
    $result = array();
    foreach ($combinations as $combination) {
        $values = array();
        foreach ($combination as $key) {
            $values[$key] = $in[$key];
        }
        $result[] = implode('-', $values);
    }
    sort($result);
    return $result;
 }

这似乎有效。

于 2017-12-03T14:25:56.873 回答