开发者

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

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 d开发者_StackOverflow中文版ynamically set the number of nested for loops to generate 4-letter or 5-letter permutations?


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


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


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


The answer is: use a recursive function.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜