简体   繁体   中英

How to print all possible variations without repetitions of array for given range?

This is what I got:

<?php 
// Program to print all 
// combination of size r 
// in an array of size n 
function printCombinations($arr, $n, $r) { 
    $data = []; 
    combinationUtil($arr, $data, 0, $n - 1, 0, $r); 
} 

function combinationUtil($arr, $data, $start, $end, $index, $r) { 
    if ($index == $r) { 
        for ($j = 0; $j < $r; $j++) {
            echo $data[$j]; 
        }
        echo "<br>"; 

        return; 
    } 

    for ($i = $start; $i <= $end && $end - $i + 1 >= $r - $index; $i++) { 
        $data[$index] = $arr[$i]; 
        combinationUtil($arr, $data, $i + 1, $end, $index + 1, $r); 
    } 
} 


$arr = [
    1,
    2,
    3,
    4,
    5
];
$r = 3; 
$n = count($arr); 
printCombinations($arr, $n, $r);

and it gives this output:

123
124
125
134
135
145
234
235
245
345

And what I need is this:

123
124
125
132
134
135
142
143
145
152
153
154
213
214
215
231
234
235
241
243
245
251
253
254
312
314
315
321
324
325
341
342
345
351
352
354
412
413
414
415
421
423
425
431
432
435
451
452
453
512
513
514
521
523
524
531
532
534
541
542
543

You can use a recursive approach, that iterates over the array, and calls itself in each iteration by removing the current element, and prepending the returned variations with it.

Something like this:

<?php
function variation_without_repetition ($array,$items){
    if($items == 0 || count($array) == 0) return [[]];
    $variations = [];
    foreach($array as $index => $item){
        if(array_search($item, $array) < $index) continue;
        $array_remaining = $array;
        array_splice($array_remaining,$index,1);
        foreach(variation_without_repetition($array_remaining,$items - 1) as $variation){
            array_unshift($variation,$item);
            $variations[] = $variation;
        }
    }
    return $variations;
}

$variations = variation_without_repetition([1,2,3,4,5], 3);
foreach($variations as $variation){
    echo implode($variation);
    echo "<br>\n";
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM