Skip to content

Instantly share code, notes, and snippets.

@dahlia
Created September 26, 2011 17:01
Show Gist options
  • Save dahlia/1242739 to your computer and use it in GitHub Desktop.
Save dahlia/1242739 to your computer and use it in GitHub Desktop.
<?php
function combinations(array $pool, $r) {
$n = count($pool);
if ($r > $n) {
return array();
}
$indices = range(0, $r - 1);
$result = array();
$tuple = array();
foreach ($indices as $i) {
$tuple[] = $pool[$i];
}
$result[] = $tuple;
while (true) {
$dup = true;
for ($i = $r - 1; $i >= 0; --$i) {
if ($indices[$i] != $i + $n - $r) {
$dup = false;
}
}
if ($dup) return $result;
++$indices[$i];
for ($j = $i + 1; $j < $r; ++$j) {
$indices[$j] = $indices[$j - 1] + 1;
}
$tuple = array();
foreach ($indices as $i) {
$tuple[] = $pool[$i];
}
$result[] = $tuple;
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment