Created
February 8, 2018 13:22
-
-
Save bdelespierre/0980c0f93cc63b883376a65865f44017 to your computer and use it in GitHub Desktop.
Array 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 array_cartesian_product(...$items): array | |
{ | |
if (empty($items)) { | |
return []; | |
} | |
if (count($items) == 1) { | |
foreach ((array) $items[0] as $value) { | |
$result[] = (array) $value; | |
} | |
} else { | |
foreach ((array) $items[0] as $value) { | |
foreach (array_cartesian_product(...array_slice($items, 1)) as $values) { | |
array_unshift($values, $value); | |
$result[] = $values; | |
} | |
} | |
} | |
return $result ?? []; | |
} | |
$values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']; | |
$colors = ["Hearts", "Tiles", "Clovers", "Spades"]; | |
$cards = array_map('implode', array_cartesian_product($values, ' of ', $colors)); | |
shuffle($cards); | |
var_dump(array_pop($cards)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment