PHP - 嵌套循环可变的次数 [英] PHP - Nest a for loop a variable number of times

查看:142
本文介绍了PHP - 嵌套循环可变的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个初学PHP(一般编程)。
为了测试我迄今为止学到的东西,我编写了这个代码,它打印了一定数量的面的一定数量的骰子的所有可能的组合。 (你会发现在最后的代码)。

我想要做的是根据动态地改变嵌套循环的数量, $ dicenumber 变量。现在它只能处理3个骰子,因为代码是:

$ p $ for($ d1 = 1; $ d1 <= ($ d3 = 1; $ d3 <= $ d3value; $($ d2); $ d1 ++){
($ d2 = 1; $ d2< = $ d2value; $ d2 ++) d3 ++){
array_push($ {sum。($ d1 + $ d2 + $ d3)},$ d1。$ d2。$ d3);





$ b

但我想改变它例如,如果 $ dicenumber 2 ,它会产生如下所示:

$ b ($ d2 = 1; $ d1 <= $ d1value; $ d1 ++){
($ d2 = 1; $ d2)
$ b

  < = $ d2value; $ d2 ++){
array_push($ {sum。($ d1 + $ d2)},$ d1。$ d2);




$ b $ p
$ b

我希望代码处理任何数字 $ dicenumber 可能是没有限制的。环顾四周,似乎我不得不添加某种递归代码,但我不知道该怎么做。有小费吗?另外,关于我做错了什么的一般反馈,将是非常有益的!

 <?php 
//定义了骰子的数量和类型
$ dicenumber = 3;
$ dtype = 6; ($ i = 1; $ i <= $ dicenumber; $ i ++){
$ {d。$ i.value} =
//定义每个骰子
的最大值$ D型;
}
//为给定数量的骰子滚动产生的每个可能的总和定义和排列。 ($ i = $ dicenumber; $ i <=($ dtype * $ dicenumber); $ i ++){
$ {sum。$ i} = array();
。 ($ d1 = 1; $ d1 <= $ d1value; $ d1 ++)


$ b //




$ ($ d3 = 1; $ d3 <= $ d3value; $ d3 ++){$ b $($ d2 = 1; $ d2< = $ d2value; $ d2 ++){
) b array_push($ {sum。($ d1 + $ d2 + $ d3)},$ d1。$ d2。$ d3);



$ b //打印所有可能的卷组合,每行列表组合共享
($ i = $ dicenumber; $ i< =($ dtype * $ dicenumber); $ i ++){
print join(,$ {sum。$ i})。< br />;
}
?>


解决方案

这里有一个双重功能的过程。第一个函数 buildArrays 以适当的格式创建数组,以供给第二个函数 allCombinations 。所以,在这个例子中,有3个D6,buildArrays会产生一个相当于这个数组的数组:

$ $ $ data $ array
阵列(1,2,3,4,5,6),
阵列(1,2,3,4,5,6),
阵列(1,2,3,4 ,5,6));

我会提醒你,随着你增加骰子数量和边数,可能的组合呈指数增长!这意味着您可以在服务器上放置一个非常大的需求,并且超时和最大内存限制都将很快发挥作用。生成的阵列可能非常非常大,并且会消耗超过最大内存限制的时间。这就是说,在这里我们去:

  function buildArrays($ dicenumber,$ dtype){

($ i = 0; $ i <$ dicenumber; $ i ++){
$ tmp = array(); ($ j = 1; $ j< = $ dtype; $ j ++){
$ tmp [] = $ j;
;
}
$ data [$ i] = $ tmp;
}
返回$ data;



$ b函数allCombinations($ data){

$ result = array(array()); //这是至关重要的,黑暗的魔法。

foreach($ data as $ key => $ array){
$ new_result = array();
foreach($ result as $ old_element){
foreach($ array as $ element){
if($ key == 0){
$ new_result [] = $ element ;
} else {
$ new_result [] = $ old_element。$ element;
}
}
$ result = $ new_result;
}
}
return $ result;
}

//设定变量
$ dicenumber = 3;
$ dtype = 6;

// set_time_limit(0); //你可能需要取消注释这个大值。

//调用函数
$ data = buildArrays($ dicenumber,$ dtype);
$ results = allCombinations($ data);

//输出结果
foreach($ results as $ result){
echo $ result。< br />;
}



N.B。这个答案是一个变种的笛卡尔的产品代码


I'm a beginner with PHP (and programming in general). To test what I've learned so far I wrote this code, which prints all the possibile combinations of a set number of dice with a certain number of faces. (you'll find the code at the end).

What I want to do is dynamically change the number of nested for loops according to the $dicenumber variable. Right now it can only process 3 dice, since the code is:

            for ($d1=1; $d1 <= $d1value ; $d1++) { 
                for ($d2=1; $d2 <= $d2value ; $d2++) { 
                for ($d3=1; $d3 <= $d3value ; $d3++) { 
                        array_push(${sum.($d1+$d2+$d3)}, "$d1"."$d2"."$d3");
                    }
                }
            }

But I want to change it so that, for example, if $dicenumber were 2, it would produce something like:

            for ($d1=1; $d1 <= $d1value ; $d1++) { 
                for ($d2=1; $d2 <= $d2value ; $d2++) { 
                        array_push(${sum.($d1+$d2)}, "$d1"."$d2");
                }
            }

I want the code to process for whatever number $dicenumber may be, without limits. Looking around, it seems like I have to add some kind of recursive code, but I don't know how to do that. Any tips? Also, any feedback on what I did wrong in general, would be extremely helpful! thanks!

            <?php
            //defines the number and type of dice
            $dicenumber = 3;
            $dtype = 6;
            //defines the maximum value of every die 
            for ($i=1; $i <=$dicenumber ; $i++) { 
                ${d.$i.value} = $dtype;
            }
            //defines and array for each possible sum resulting from the roll of the given number of dice. 
            for ($i=$dicenumber; $i <= ($dtype*$dicenumber) ; $i++) { 
            ${sum.$i} = array();
            }

            //the troublesome piece of code I want to change    

            for ($d1=1; $d1 <= $d1value ; $d1++) { 
                for ($d2=1; $d2 <= $d2value ; $d2++) { 
                for ($d3=1; $d3 <= $d3value ; $d3++) { 
                        array_push(${sum.($d1+$d2+$d3)}, "$d1"."$d2"."$d3");
                    }
                }
            }

            //prints all the possible roll combinations, each line lists combination that share the same sum
            for ($i=$dicenumber; $i <= ($dtype*$dicenumber); $i++) { 
        print join(" ", ${sum.$i})."<br />";
        }
        ?>

解决方案

Here we have a two-function process. The first function, buildArrays, creates arrays in the proper format to feed into the second function, allCombinations. So, for this example with 3 d6's in play, buildArrays will produce an array equivalent to this:

$data = array(
    array(1, 2, 3, 4, 5, 6),
    array(1, 2, 3, 4, 5, 6),
    array(1, 2, 3, 4, 5, 6));

I will warn you that as you increase the number of dice and the number of sides, the number of possible combinations increases exponentially! This means that you could place a very large demand on the server, and both timeout and max memory limits will quickly come into play. The arrays generated could be very, very large and quickly consume more than the max memory limit. That said, here we go:

function buildArrays($dicenumber, $dtype){

    for ($i = 0; $i<$dicenumber; $i++){
        $tmp = array();
        for ($j = 1; $j<=$dtype; $j++){
            $tmp[] = $j;
        }
        $data[$i] = $tmp;
    }
    return $data;
}



function allCombinations($data){

    $result = array(array()); //this is crucial, dark magic.

    foreach ($data as $key => $array) {
        $new_result = array();
        foreach ($result as $old_element){
            foreach ($array as $element){
                if ($key == 0){
                    $new_result[] = $element;
                } else {
                    $new_result[] = $old_element.$element;
                }
            }
        $result = $new_result;
        }
    }
    return $result;
}

//set variables
$dicenumber = 3;
$dtype = 6;

//set_time_limit(0); //You may need to uncomment this for large values.

//call functions
$data = buildArrays($dicenumber, $dtype);
$results = allCombinations($data);

//print out the results
foreach ($results as $result){
    echo $result."<br/>";   
}

N.B. This answer is a variant of the cartesian product code

这篇关于PHP - 嵌套循环可变的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆