1

I want the combination of the number 1 to nth.

Example sets:

Number Range: 1,2,3

Combination of output in 2 digits ( if number range is 1 to 4 then I want it in 2 or 4 digit. So it's dynamic base on the number range)

Output:

1,2
1,3
2,3
3,1 
etc...

If Combination of output in 3 digits

Output:

1,2,3
2,1,3
1,3,2
3,1,2
2,3,1
3,2,1 
etc...

I have tried below function for the combination but I want it in 2 digit

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        $return = array($perms);
    }  else {
        $return = array();
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
         list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             $return = array_merge($return, pc_permute($newitems, $newperms));
         }
    }
    return $return;
}
echo "<br> <pre>";
$value = array('1', '2', '3');
print_r(pc_permute($value));
LF00
  • 27,015
  • 29
  • 156
  • 295
CBA
  • 192
  • 1
  • 13
  • Look [here](https://stackoverflow.com/questions/56234369/next-permutation-in-lexicographic-order-n-k/56241837#56241837) for Python implementation and [here](https://stackoverflow.com/questions/38390689/all-permutation-of-an-array-elements-taken-certain-number-of-element-at-a-time-i/38391319#38391319) for Delphi and C++ ones – MBo Oct 16 '19 at 05:58

2 Answers2

1

try below implemantaion:

function combinations($items, $size, $combo = array()) {    
    if (empty($combo)) {
        $combo = $items;
    }   
    if ($size == 1) {
        return $combo;
    }    
    $new_combo = array();   
    foreach ($combo as $combination) {
        foreach ($items as $i) {
            $new_combo[] = $combination .','. $i;
        }
    }    
    return combinations($items, $size - 1, $new_combo);

}
$items = array(1,2,3);
$output = combinations($items, 2);
print_r($output);

output:Array ( [0] => 1,1 [1] => 1,2 [2] => 1,3 [3] => 2,1 [4] => 2,2 [5] => 2,3 [6] => 3,1 [7] => 3,2 [8] => 3,3 )
Divyesh patel
  • 967
  • 1
  • 6
  • 21
1

Do it recersively. Demo

function n_combinations($values,$length){
    if($length == 1){
        return $values;
    }else{
        $result = [];
        foreach($values as $value){
            foreach(n_combinations($values,$length-1) as $value_1){
                $result[] = "$value,$value_1";
            }
        }
        return $result;
    }
}
LF00
  • 27,015
  • 29
  • 156
  • 295