生成数字的组合组合、数字

2023-09-10 23:41:36 作者:深情是一场慢性自杀

我有一个PHP页面有两个变量: $ nbRank $ nbNumeric 。根据这两个变量,欲生成包含现有的所有组合的阵列。例如:

I have a PHP page with two variables: $nbRank and $nbNumeric. Depending of these two variables, I want to generate an array containing all combinations existing. For example:

如果 $ nbRank = 3 $ nbNumeric = 2 我会有:

0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
1 2 0
1 2 1
1 2 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2
2 2 0
2 2 1
2 2 2

所以,我创建不同的环路和公式来获得最终的结果,但它不工作。这是我做的:

So, I create different loop and formulas to get the final result, but it doesn't works. This is what I did :

$result = array();

$nbIntRank = 0;
$nbIntNumeric = 0;
$nbRank = array();
$nbNumeric = array();

$nb_rangs = 3;
$nb_chiffres = 2;

for ($i = 1; $i <= $nb_rangs; $i++){
    $nbRank[$i] = 0;
}

$nbIntRank = count($nbRank);

for ($i = 0; $i <= $nb_chiffres; $i++){
    $nbNumeric[$i] = $i;
}

$nbIntNumeric = count($nbNumeric);

$algo = ($nb_rangs * ($nb_chiffres + 1)) * ($nb_rangs * ($nb_chiffres + 1));
$nbLine = $algo / ($nb_rangs);

$occ = 0;
for ($i = 0; $i < $nbLine; $i++){
    foreach ($nbRank as $nbrItem => $nbrValue){
        $result[$i][] = $nbrValue;
        $occ++;
    }
}

echo '#############<br />';
echo '### DATAS ###<br />';
echo '#############<br /><br />';

echo '- Nb Elements : '.$algo.'<br />';
echo '- Nb Lines : '.$nbLine.'<br />';
echo '- Nb Valuable Occurency : '.$occ.'<br />';

echo '<br /><hr /><br />';
echo '##############<br />';
echo '### PARSER ###<br />';
echo '##############<br /><br />';

echo '<pre>';
var_dump($result);
echo '</pre>';

我设法创建我的空值的最后一个数组(81值,在27行的3个元素),但它仅包含0。

I managed to create my final array with empty values (81 values, in 27 lines of 3 elements) but it only contains 0.

推荐答案

下面是一个递归解决方案:

Here's a recursive solution:

$nbRank = 3;
$nbNumeric = 2;

function getCombinations ($length, $min, $max, $aStartingCombinations)
{
    if ($length == 1)
    {
        return range ($min, $max);
    }

    $final = array ();
    foreach (getCombinations ($length - 1, $min, $max, $aStartingCombinations) as $combination)
    {
        for ($i = $min; $i <= $max; $i++)
        {
            $final [] = $combination . $i;
        }
    }
    return $final;
}

print_r (getCombinations ($nbRank, 0, $nbNumeric, array ()));
 
精彩推荐
图片推荐