Skip to content

Instantly share code, notes, and snippets.

@oranj
Created August 20, 2012 19:38
Show Gist options
  • Save oranj/3407106 to your computer and use it in GitHub Desktop.
Save oranj/3407106 to your computer and use it in GitHub Desktop.
Generate Combinations of a set
<?php
function generate_combinations($set, $max_depth = INF, $depth = 0) {
if (! is_array($set)) { trigger_error("Give me an array plox"); }
if (count($set) <= 1) {
return array($set);
}
if ($depth >= $max_depth) {
return array($set);
}
$mantissa = reset($set);
$subset = array_slice($set, 1);
$combinations = generate_combinations($subset, $max_depth, $depth + 1);
$add_combos = array();
foreach ($combinations as $subset) {
$add_combos []= array_merge(array($mantissa), $subset);
}
foreach ($add_combos as $subset) {
$combinations []= $subset;
}
return $combinations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment