Created
August 20, 2012 19:38
-
-
Save oranj/3407106 to your computer and use it in GitHub Desktop.
Generate Combinations of a set
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 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