开发者

Recursively find combinations in PHP

开发者 https://www.devze.com 2023-02-16 09:19 出处:网络
I have the following structure: A   3 B   2 C   2 D   1 E   0

I have the following structure:

A   3

B   2

C   2

D   1

E   0

While letters represent the actual value of the element, numbers represent the level of the element. I want to be able to output the following:

A B D E

A C D E

the code that I have right now is not doing the job properly and I need to find a recursive way to address the problem. Any help would be really appreciated.

<?php

// An array that holds the values
$values = array();
$values[] = "A";
$values[] = "B";
$values[] = "C";
$values[] = "D";
$values[] = "E";


// An array that holds the levels
$levels = array();
$levels[] = 3;
$levels[] = 2;
$levels[] = 2;
$levels[] = 1;
$levels[] = 0;

// We are asuming that 3 is the heighest level
$startingLevel = 3;


// this array will holds all combinations. each group is seperated by a |
$results = array();


for($i = 0; $i < count($values); $i++)
{
    $thisValue = $values[$i];
    $thisLevel = $levels[$i];

    if($thisLevel == $startingLevel)
    {
        $results[] = $thisValue;
        $j = 0;
        $k = $i;
        $limit = $thisLevel;        

        while($j < $thisLevel)
        {
            if($levels[$k] < $limit)
            {
                $results[] = $values[$k];
                $limit = $levels[$k];
                $j++;
            }

            $k++;
        }

            // separating group开发者_Go百科s by |
        $results[] = "|";
    }

}


// Show results
print_r($results);

?>


Most likely what you want is to generate all combinations with O((n^2-n)/2) and then compare it with the 2nd array and also what you want is to look at my example in Javascript. Array Waypoints hold your first Array. Array wayStr holds your solution. Then you need only to iterate through the solution and compare it with your 2nd array.

function getWayStr(curr) {
   var nextAbove = -1;
   for (var i = curr + 1; i < waypoints.length; ++i) {
     if (nextAbove == -1) {
       nextAbove = i;
     } else {
        wayStr.push(waypoints[i]);
        wayStr.push(waypoints[curr]);
     }
    }
    if (nextAbove != -1) {
      wayStr.push(waypoints[nextAbove]);
      getWayStr(nextAbove);
      wayStr.push(waypoints[curr]);
    }
   } 


Separate the different levels and use permutation: lexicographic ordering

0

精彩评论

暂无评论...
验证码 换一张
取 消