【问题标题】:Create array with all the permutations of another array of natural numbers with PHP使用 PHP 创建具有另一个自然数数组的所有排列的数组
【发布时间】:2011-09-19 08:48:59
【问题描述】:

我用 $my_array = range(1,3) 创建了一个数组,我想创建一个数组,其中包含这个数组的所有排列 (1,2,3 1,3,2 2,1 ,3 ..)。

范围函数中的第二个数字可以更改(可以是 4、5、7、50 而不是 3)。

【问题讨论】:

标签: php arrays permutation


【解决方案1】:

来自Christer's blog o' fun 的代码:

function permute($str) {
    /* If we only have a single character, return it */
    if (strlen($str) < 2) {
        return array($str);
    }

    /* Initialize the return value */
    $permutations = array();

    /* Copy the string except for the first character */
    $tail = substr($str, 1);

    /* Loop through the permutations of the substring created above */
    foreach (permute($tail) as $permutation) {
        /* Get the length of the current permutation */
        $length = strlen($permutation);

        /* Loop through the permutation and insert the first character of the original
        string between the two parts and store it in the result array */
        for ($i = 0; $i <= $length; $i++) {
            $permutations[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i);
        }
    }

    /* Return the result */
    return $permutations;
}

$array_of_natural_numbers = range(1, 5);
$string_of_natural_numbers = implode("",$array_of_natural_numbers);
$permutations = permute($string_of_natural_numbers);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多