简体   繁体   English

如何在给定范围内不重复数组的情况下打印所有可能的变化?

[英]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:它给出了这个 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";
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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