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

痴心易碎 提交于 2019-12-04 16:46:33

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

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

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.

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