is it possible to dynamically set the level of for loop nesting

痞子三分冷 提交于 2019-12-12 09:10:13

问题


I'm working out an algorithm to get permutations like

123
132
213
231
312
321

I'm doing it using nested foreach loops.

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

Problem is those # of nested loops are optimized for 3-spot permutations. How can I could I dynamically set the number of nested for loops to generate 4-letter or 5-letter permutations?


回答1:


Recursive method is the way to go. But you can also use eval function like:

$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}++)";    
}



回答2:


Yes, just do it recursively.

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:


No, no, please do NOT use recursion for generating permutations. Use the algorithm outlined here, see also php implementation




回答4:


The answer is: use a recursive function.




回答5:


You could use a recursive function. Take a look at this post.



来源:https://stackoverflow.com/questions/2529508/is-it-possible-to-dynamically-set-the-level-of-for-loop-nesting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!