Last active
February 3, 2024 13:14
-
-
Save phcorp/c18b1d3bcb87ff75e5edeb014340d73d to your computer and use it in GitHub Desktop.
Cartesian product
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 | |
function multiply(...$sets): array | |
{ | |
if (!$sets) { | |
return [[]]; | |
} | |
$set = array_shift($sets); | |
$products = multiply(...$sets); | |
$result = []; | |
foreach ($set as $value) { | |
foreach ($products as $product) { | |
array_unshift($product, $value); | |
$result[] = $product; | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment