PHP给定按此顺序递增的数字,计算所有可能的组合


PHP Given increasing numbers in this order, calculate all possible combinations

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

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

我需要获得这些数字的所有组合,除了数字不能排列,所以顺序是保持的,我将举一个我试图获得的例子:

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

所得数组将包含所得数字的子数组

更新:空数组是可选的,

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

也可以,并发症更少。

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

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 ) );

基本上,我所做的是用这个答案的代码找出所有可能的"数字在那里"/"数字不在那里"组合,如下所示:

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变量包含您想要的值(如果数字不存在)。

只需点击此链接并选择"跑步":http://phpfiddle.org/main/code/fdtn-u5jv