简体   繁体   中英

Print all combination of sub range within a given array

I want to print all combination of sub range in an given array. I have an array of y number of elements in it from which I want to print all combination of contiguous sub range.

Constraint is : each sub range should have at least 2 elements and each element in sub range should be contiguous. It should share same border of each element.

For example, We have an array of 7 elements [11,12,13,14,11,12,13]

So, the total number of sub range combination will [7 * (7-1) /2] = 21

So, the Output will be something like this:

11,12

12,13

13,14

14,11

11,12

12,13

11,12,13

12,13,14

13,14,11

...

11,12,13,14 and so on (total 21 combination as per above array)

we should not print any combination which is not contiguous. example: [11,12,14] is not valid combination as it skips the element "13" in between.

I am able to print the combination with 2 elements but i am having difficulty in printing more then 2 elements combination.

Below is what I have tried so far.

$data=array("11","12","13","14","11","12","13");
$totalCount=count($data);

for($i=0;$i<$totalCount;$i++){
    if(($i+1) < ($totalCount)){
        echo "[".$data[$i].",".$data[$i+1]."]<br>";
    }
}

You can do that:

$arr = [11,12,13,14,11,12,13];

function genComb($arr, $from = 1, $to = -1) {
    $arraySize = count($arr);
    if ($to == -1) $to = $arraySize;
    $sizeLimit = $to + 1;
    for ($i = $from; $i < $sizeLimit; $i++) { // size loop
        $indexLimit = $arraySize - $i + 1;
        for ($j = 0; $j < $indexLimit; $j++) { // position loop
            yield array_slice($arr, $j, $i);
        }
    }
}

$count = 0;
foreach (genComb($arr, 2) as $item) {
    echo implode(',', $item), PHP_EOL;
    $count++;
}

echo "total: $count\n";

Casimir et Hippolyte was faster, but you can gain huge performance by processing each contiguous section independently:

function getCombos(&$data) {
    $combos = array();
    $count = count($data);
    $i = 0;
    while ($i < $count) {
        $start = $i++;
        while ($i < $count && $data[$i - 1] + 1 == $data[$i]) // look for contiguous items
            $i++;
        if ($i - $start > 1) // only add if there are at least 2
            addCombos($data, $start, $i, $combos); // see other answer
    }
    return $combos;
}

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