PHP根据此顺序增加数字,计算所有可能的组合

时间:2015-11-01 14:40:44

标签: php arrays math multidimensional-array

问题很简单,但令我头疼, 我有一个4号数组,但我最多可以有20个数字。 按以下顺序给出:

       [1]  [2]  [4]  [5]

我需要获得这些数字的所有组合,除了数字不能被置换,所以维持顺序,我将举例说明我想要获得的数据:

     [1] [ ] [4] [5]
     [1] [2] [ ] [5]
     [ ] [2] [4] [5]
     [ ] [ ] [ ] [5]
     and even
     [ ] [ ] [ ] [ ]

结果数组将包含结果数字的子数组

更新:空数组是可选的,

          [1] [4] 

               Or

           [2] [4] [5]

也可以,减少并发症。

2 个答案:

答案 0 :(得分:2)

基本上,我所做的是我用this answer's代码找出所有可能的"数字是否存在" /"数字不存在"组合,如下所示:

0 0 0 0
1 0 0 0
1 1 0 0
1 1 1 0
1 1 1 1
0 1 0 0
and so on...

之后我将其应用于input数组内容。

<?php
//First of all, find out all possible combinations of "number is there" and "number is not there"

$input = ["1","2","4","5"];

$empty = " "; //Value to insert if "number is not there"

$length = sizeof($input); //How many numbers are in the array

$combinations = pow(2, $length); //Number of possible 1/0 combinations

$sequence = array();

for($x = 0; $x < $combinations; $x++) {
    $sequence[$x] = str_split(str_pad(decbin($x), $length, 0, STR_PAD_LEFT));
}

//Alright, so now we have to apply these combinations to our $input array
$output = [];


foreach($sequence as $combo){
    $output_combo = [];
    foreach($combo as $key=>$val){
        if ($val == 1){
            //"number is there"
            array_push($output_combo, $input[$key]);
        }else{
            //"number is not there"
            array_push($output_combo, $empty);
        }
    }
    array_push($output, $output_combo);
}

//There you go! The variable $output contains your array.

//Display the array (You can leave this part out...)
foreach($output as $combo){
    foreach($combo as $val){
        echo "[" . $val .  "] ";
    }
    echo "<br>";
}

?>

查看这个PHPFiddle - 它可以使用任意数量的数字。如果数字不存在,只需确保$empty变量包含您想要的值。

只需点击此链接,然后选择&#34;运行&#34;:http://phpfiddle.org/main/code/fdtn-u5jv

答案 1 :(得分:2)

如果您意识到我们想要实现的目标实际上是递归的,那么您想要做的事情可以很容易地完成。对于每个子部分,我们需要做出选择:我们添加一个空格,或者从列表中添加一个数字。

function wonkyPermutations( $numbers ) {
  return wonkyPermutationsWithSpaces( Array(), $numbers, count( $numbers ) );
}

function wonkyPermutationsWithSpaces( $prefix, $numbers, $maxlength ) {
  if( $maxlength == 0 ) {
    //We can't add anymore
    return Array( $prefix );
  } else {
    //We have two choices: We either add a space, or we don't.
    $prefix1 = $prefix;
    $prefix1[] = NULL;
    $prefix2 = $prefix;
    $prefix2[] = $numbers[0];
    $suffix1 = wonkyPermutationsWithSpaces( $prefix1, array_slice( $numbers, 1 ), $maxlength - 1 );
    $suffix2 = wonkyPermutationsWithSpaces( $prefix2, array_slice( $numbers, 1 ), $maxlength - 1 );

    return array_merge( $suffix1, $suffix2 );
  }
}

$a = Array( 1, 2, 3, 4 );
var_dump( wonkyPermutations( $a ) );