Home > Mobile >  All Combinations of one Array with 2 connectors
All Combinations of one Array with 2 connectors

Time:07-11

My problem is relatively simple but I cannot figure it out a reasonable algorithm by myself

I have an array which can be any length (n>=2), and I want to connect the elements with 2 separators ( '_' and ' ' ):

So for example when my array has 2 elements [0,1] the result would be [0_1, 0 1]

For 3 elements [0,1,2]

0_1_2,
0 1 2, 
0 1_2, 
0_1 2,  
0_2 1

For 4 elements [0,1,2,3]

0_1_2_3,
0 1 2 3, 
0 1_2_3, 
0_1 2_3, 
0_1_2 3, 
0_2 1 3,
0_2 1_3,
0_3 1 2,
0_3 1_2

For 5 elements [0,1,2,3,4]

0_1_2_3_4, 
0 1_2_3_4, 
0_1 2_3_4, 
0_1_2 3_4,
0_1_2_3 4,  
0 1 2 3 4,
0_2 1 3 4,
0_2 1_3_4,
0_2 1 3_4,
0_2 1_3 4,
...

I hope this explanation is somewhat clear.

CodePudding user response:

Not sure if this hits spec, but its a start:

$new = [];
$arr = [1,2,3,4,5];
for($i=0;$i<count($arr);$i  ) {
    $new[] = implode("_",$arr);
    $arr[] = array_shift($arr);
}

foreach($new as $n) {
    $o = $n;
    while(strpos($o,"_")) {
        $o = preg_replace("/_/"," ",$o,1);
        $new[] = $o;
    }

    $o = strrev($n);
    while(strpos($o,"_")) {
        $o = preg_replace("/_/"," ",$o,1);
        $new[] = $o;
    }
}

print_r($new);
  • Related