php - php中x pow y的所有组合

标签 php math combinations

我有一个包含三个元素的数组 $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。

最佳答案

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

// 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

关于php - php中x pow y的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12369443/

相关文章:

Prolog:如何获得所有组合

php - 我在一个销售不同艺术品的网站上工作,处理不同图像尺寸的最佳方法是什么?

PHP 文件上传.. 检索 URL

php - 使用 Laravel Auth 伪造登录

math - 计算椭圆上的一个点

excel - 无论它们的顺序如何,如何检查相同的值组合

php - 如果有 4 行或更多行以用户名命名,如何删除行

algorithm - 如何以编程方式求解 y = (a1 * x1) + (a2 * x2) + .... + (a28 * x28) 其中 y 和 a1、a2 ....a28 已知?

c++ - 我可以依靠它来判断 C++ 中的平方数吗?

ios - 随机显示一对用户,并且不再显示同一对用户