【问题标题】:is it possible to dynamically set the level of for loop nesting是否可以动态设置for循环嵌套的级别
【发布时间】:2011-02-01 12:54:59
【问题描述】:

我正在研究一种算法来获得类似的排列

123
132
213
231
312
321

我正在使用嵌套的 foreach 循环。

for (..) {
    for(..) {
        for(..) {
           echo $i . $j . $k . "<br />";
        }   
    }
}

问题是那些 # 嵌套循环针对 3 点排列进行了优化。 如何动态设置嵌套 for 循环的数量以生成 4 字母或 5 字母排列?

【问题讨论】:

    标签: php nested for-loop


    【解决方案1】:

    不,不,请不要使用递归来生成排列。使用here 概述的算法,另请参阅php implementation

    【讨论】:

      【解决方案2】:

      是的,只需递归即可。

      function permuteThis($items, $permutations = array()) {
      
          if(!is_array($items))
              $items = str_split($items);
      
          $numItems = sizeof($items);
      
          if($numItems > 0) {
              $cnt = $numItems - 1;
              for($i = $cnt; $i >= 0; --$i) {
                  $newItems   = $items;
                  $newPerms   = $permutations;
                  list($tmp)  = array_splice($newItems, $i, 1);
                  array_unshift($newPerms, $tmp);
                  permuteThis($newItems, $newPerms);
              }
          } else {
              echo join('', $permutations) . "\n";
          }
      }
      
      $number = 123;
      permuteThis($number);
      

      【讨论】:

        【解决方案3】:

        递归方法是要走的路。但您也可以使用eval 函数,例如:

        $loop = iteration('i',10) . iteration('j',10). iteration('k',10). iteration('l',10);
        $loop .= "print \"\$i \$j \$k \$l\\n\";";
        
        // $loop now has: for($i=0;$i<10;$i++)for($j=0;$j<10;$j++)for($k=0;$k<10;$k++)for($l=0;$l<10;$l++) print "$i $j $k $l\n";
        eval($loop);
        
        function iteration($var,$limit) {
            return "for(\${$var}=0;\${$var}<$limit;\${$var}++)";    
        }
        

        【讨论】:

          【解决方案4】:

          您可以使用递归函数。看看这个post

          【讨论】:

            【解决方案5】:

            答案是:使用递归函数。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2016-04-22
              • 2021-07-14
              • 1970-01-01
              • 2019-10-02
              • 2010-10-03
              • 2011-03-26
              • 2012-12-01
              相关资源
              最近更新 更多