是否可以动态设置for循环嵌套的级别

gal*_*axy 2 php for-loop nested

我正在制定一种算法来获得像这样的排列

123
132
213
231
312
321
Run Code Online (Sandbox Code Playgroud)

我正在使用嵌套的 foreach 循环来完成此操作。

for (..) {
    for(..) {
        for(..) {
           echo $i . $j . $k . "<br />";
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lex 5

是的,只需递归地执行即可。

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);
Run Code Online (Sandbox Code Playgroud)