drzbc6003 2012-04-13 23:22
浏览 13
已采纳

生成数字组合

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:

If $nbRank = 3 and $nbNumeric = 2 I would have:

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>';

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

  • 写回答

3条回答 默认 最新

  • dou4381 2012-04-13 23:41
    关注

    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 ()));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)