-
-
Save mocheng/831165 to your computer and use it in GitHub Desktop.
Solution and forked from https://gist.github.com/830201
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arr = array( | |
'Color' => array('Red', 'Blue'), | |
'Size' => array('Regular', 'Large'), | |
'Material' => array('Metalic', 'Nylon') | |
); | |
function magic_algorithm($arr){ | |
function cartesian_product($arrays) { | |
$result = array(); | |
if (count($arrays) == 0) { | |
return array(array()); | |
} | |
reset($arrays); | |
$first_key = key($arrays); | |
$first_array = array_shift($arrays); | |
$rec = cartesian_product($arrays); | |
foreach ($first_array as $v) { | |
foreach ($rec as $tail) { | |
$result []= array_merge(array($first_key => $v), $tail); | |
} | |
} | |
return $result; | |
} | |
$product = cartesian_product($arr); | |
$result = array(); | |
foreach ($product as $row) { | |
$line = array(); | |
foreach ($row as $key => $val) { | |
$line []= "$key: $val"; | |
} | |
$result []= join("; ", $line); | |
} | |
return $result; | |
} | |
$result = magic_algorithm($arr); | |
$expected = array( | |
"Color: Red; Size: Regular; Material: Metalic", | |
"Color: Red; Size: Regular; Material: Nylon", | |
"Color: Red; Size: Large; Material: Metalic", | |
"Color: Red; Size: Large; Material: Nylon", | |
"Color: Blue; Size: Regular; Material: Metalic", | |
"Color: Blue; Size: Regular; Material: Nylon", | |
"Color: Blue; Size: Large; Material: Metalic", | |
"Color: Blue; Size: Large; Material: Nylon" | |
); | |
echo ($expected == $result) ? "Passed" : "Failed"; | |
print_r($result); | |
echo "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment