Skip to content

Instantly share code, notes, and snippets.

@swvitaliy
Created July 30, 2014 08:37
Show Gist options
  • Save swvitaliy/c32f51641cf2c4e7b241 to your computer and use it in GitHub Desktop.
Save swvitaliy/c32f51641cf2c4e7b241 to your computer and use it in GitHub Desktop.
function cartesianProduct(array $arrayOfSets, array $tuple = array(), $n = 0) {
$size = count($arrayOfSets);
if ($n === $size) {
return array();
}
$result = array();
$set = $arrayOfSets[$n];
foreach($set as $itemOfSet) {
// добавляем элемент множества в н-ку
array_push($tuple, $itemOfSet);
// рекурсивно вызываем метод, который начинает обход со следующего множества в наборе
if (($n + 1) === $size) {
$result []= array_slice($tuple, 0);
} else {
$resultOfNextSets = cartesianProduct($arrayOfSets, $tuple, $n + 1);
foreach ($resultOfNextSets as $set) {
$result []= array_slice($set, 0);
}
}
array_pop($tuple);
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment