is it possible to dynamically set the level of for

2019-04-14 17:16发布

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?

5条回答
我命由我不由天
2楼-- · 2019-04-14 17:57

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楼-- · 2019-04-14 17:59

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}++)";    
}
查看更多
闹够了就滚
4楼-- · 2019-04-14 18:05

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

查看更多
叛逆
5楼-- · 2019-04-14 18:15

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

查看更多
神经病院院长
6楼-- · 2019-04-14 18:18

The answer is: use a recursive function.

查看更多
登录 后发表回答