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

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

WBOY
Release: 2016-06-06 20:17:59
Original
1329 people have browsed it

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

从数组$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>
Copy after login
Copy after login

从数组$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>
Copy after login

用递归可以实现

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template