0

input $chmcs is a 3 dim. array. Expected output is a 2 dim. array of each combination of 1 dim. arrays from $chmcs.

Example $chmcs:

$chmcs[] = [['e1']];
$chmcs[] = [['e2'],['e3']];
$chmcs[] = [['e4','e5'],['e6'],['e7','e8']];

for the example $chmcs above, expected, correct 2 dim. array output must have 6 combinations:

[
    ['e1', 'e2', 'e4', 'e5'],
    ['e1', 'e2', 'e6'],
    ['e1', 'e2', 'e7', 'e8'],
    ['e1', 'e3', 'e4', 'e5'],
    ['e1', 'e3', 'e6'],
    ['e1', 'e3', 'e7', 'e8']
]

However the function I tried below gives this incorrect output:

my function's incorrect output:

[
    ['e1', 'e2'],
    ['e1', 'e3'],
    ['e1', 'e2', 'e4', 'e5'],
    ['e1', 'e2', 'e6'],
    ['e1', 'e2', 'e7', 'e8'],
    ['e1', 'e3', 'e4', 'e5'],
    ['e1', 'e3', 'e6'],
    ['e1', 'e3', 'e7', 'e8']
]

What is wrong with my function? May you help me for a correct function? thanks, regards.

$chmcs[] = [['e1']];
$chmcs[] = [['e2'],['e3']];
$chmcs[] = [['e4','e5'],['e6'],['e7','e8']];

function mcs_and(array $chmcs) : array
{
    $rootmcs = []; //output
    if (count($chmcs) < 2) {
        throw new Exception;
    }
    while ( ! empty($chmcs)) {
        $cur1 = array_shift($chmcs);
        $cur2 = array_shift($chmcs);
        foreach ($cur1 as $c1) {
            foreach ($cur2 as $c2) { 
                $rootmcs[] = array_unique(array_merge($c1, $c2));
            }
        }
        if (empty($chmcs)) {
            return $rootmcs;
        }
        array_unshift($chmcs, $rootmcs);
    }
}

print_r(mcs_and($chmcs));
Ersin
  • 124
  • 3
  • Your expected output currently contains the exact same three elements twice. Surely, for the second half, it should say `e3` in the second position, and not `e2`? – CBroe Feb 25 '22 at 08:41
  • thanks. i edited & corrected my question. – Ersin Feb 25 '22 at 08:43
  • yes it does; however, my concern is to understand where my function fails, thanks. – Ersin Feb 25 '22 at 08:49
  • 1
    While the question seems similar to the link in the 'Question closed', I do not think that it is the exact same problem. I would suggest to reopen the question. – lukas.j Feb 25 '22 at 09:13

0 Answers0