【问题标题】:all combination of x pow y in phpphp中x pow y的所有组合
【发布时间】:2012-09-04 08:49:27
【问题描述】:

我有一个包含三个元素的数组 $base =(#m, #f,#p)

我有第二个数组,其中包含任意数量的元素,例如 $var = (s1, s2)

现在我需要仅根据基本数组创建所有可能的组合。我找到的公式是x pow y

在这个例子中,我的基本数组有三个元素,$var2,所以 pow(3, 2)9。我需要这九种组合。即

#m#m #m#f #m#p
#f#m #f#f #f#p
#p#m #p#f #p#p

第二个数组中元素的数量实际上就是生成的组合的长度。如本例所示,第二个数组的长度为 2,因此所有生成的字符串的长度均为 2。

【问题讨论】:

  • 您只需要一个嵌套循环和一个n-D array
  • 第二个数组与第一个数组有什么关系?我看不出它有什么关系。
  • @DaveRandom 考虑具有 3 个值的第二个数组。结果将是一个 3x3x3 数组。
  • 那么与第二个数组唯一相关的是它包含的元素数量?
  • 随机的$# 是怎么回事?

标签: php math combinations


【解决方案1】:

你可以像这样使用递归函数:

// input definition
$baseArray = array("#m", "#f", "#p");
$varArray = array("s1", "s2", "s3");

// call the recursive function using input
$result = recursiveCombinations($baseArray, sizeof($varArray));

// loop over the resulting combinations
foreach($result as $r){
    echo "<br />combination " . implode(",", $r);
}

// this function recursively generates combinations of #$level elements
// using the elements of the $base array
function recursiveCombinations($base, $level){
    $combinations = array();
    $recursiveResults = array();

    // if level is > 1, get the combinations of a level less recursively
    // for level 1 the combinations are just the values of the $base array
    if($level > 1){
        $recursiveResults = recursiveCombinations($base, --$level);
    }else{
        return $base;   
    }
    // generate the combinations
    foreach($base as $baseValue){
        foreach($recursiveResults as $recursiveResult){
            $combination = array($baseValue);
            $combination = array_merge($combination, (array)$recursiveResult);  
            array_push($combinations, $combination);
        }
    }
    return $combinations;
}

Working codepad demo

【讨论】:

  • 完美,我可以看到这对我很有用。如果发现任何问题,我会处理并更新它。你太棒了:)
  • 太好了,很高兴我能帮上忙!祝你好运!
【解决方案2】:
<?php
    $strs = Array("some", "thing", "here");
    $poss = Array(1, 2);
    $new = Array();
    for($i = 0; $i < pow(count($strs), count($poss)); $i++) {
        for($j = 0; $j < count($strs); $j++) {
            $new[$i] = $strs[($i%count($strs))] . " " . $strs[$j];
        }
    }
    print_r($new);
?>

Working codepad 链接(例如)。

链接

【讨论】:

  • 如果你改变 $poss = Array(1, 2,3) ,即长度变为三,它应该生成长度为三的值,而此代码生成长度为二的值,与大小无关$可能
  • 这似乎不起作用,除非我误解了这个问题。如果您使用 OP 的输入,您会得到 3 组相同的 3 组组合。
猜你喜欢
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多