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

核能气质少年 提交于 2020-06-28 05:19:33

问题


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

回答1:


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";
}
?>


来源:https://stackoverflow.com/questions/61302671/how-to-print-all-possible-variations-without-repetitions-of-array-for-given-rang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!