Home  >  Article  >  Backend Development  >  从a-f六个字符中取出3-4个字符进行组合该怎么做?

从a-f六个字符中取出3-4个字符进行组合该怎么做?

WBOY
WBOYOriginal
2016-06-06 20:17:591277browse

<code>$arr=['a','b','c','d','e','f'];</code>

从数组$arr中取出3个或4个字符(两种情况都考虑)组合成新的字符,比如abc,abd,abe,abcd等,同时考虑顺序不同的情况,abc和acb视为不同的情况,将新的字符存入数组,
$newArr[]='abc';
$newArr[]='abd';
$newArr[]='abe';
$newArr[]='abcd';
$newArr[]='acbd';
...

怎样列举所有的情况?

回复内容:

<code>$arr=['a','b','c','d','e','f'];</code>

从数组$arr中取出3个或4个字符(两种情况都考虑)组合成新的字符,比如abc,abd,abe,abcd等,同时考虑顺序不同的情况,abc和acb视为不同的情况,将新的字符存入数组,
$newArr[]='abc';
$newArr[]='abd';
$newArr[]='abe';
$newArr[]='abcd';
$newArr[]='acbd';
...

怎样列举所有的情况?

<code>function dfs($pre, $chars, $arr, $lenArr) {
    if(!empty($pre) && in_array(strlen($pre), $lenArr)){ $arr[] = $pre; }
    if(!empty($chars)) {
        foreach ($chars as $char) {
            $tempChars = array();
            foreach ($chars as $c) {
                if ($c !== $char) { $tempChars[] = $c; }
            }
            $arr = $this->dfs($pre.$char, $tempChars, $arr, $lenArr);
        }
    }
    return $arr;
}

function get_combine() {
    $chars = array('a', 'b', 'c', 'd', 'e', 'f');
    $combineArray = array();
    $combineArray = $this->dfs('', $chars, $combineArray, array(3, 4));
    echo count($combineArray).'<br>';
    var_dump($combineArray);
}

</code>

用递归可以实现

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn