Skip to content

Instantly share code, notes, and snippets.

@nicmart
Last active February 9, 2016 16:41
Show Gist options
  • Save nicmart/27ba1ceb7a7446820947 to your computer and use it in GitHub Desktop.
Save nicmart/27ba1ceb7a7446820947 to your computer and use it in GitHub Desktop.
Enumerate all the subsets of a set of a given size
<?php
/**
* @author Nicolò Martini - <[email protected]>
*
* Created on 05/02/2016, 19:52
*/
namespace NicMart;
/**
* Class SubsetEnumerator
* @package Dxi\Backend\Reporting\Index\Column
*/
class FixedSizeSubsetEnumerator
{
public function getSubsets(array $set, $subsetsSize)
{
$setSize = count($set);
if ($subsetsSize > $setSize) {
return array();
}
$indexes = array();
for ($i = 0; $i < $subsetsSize; $i++) {
$indexes[$i] = $i;
}
$subsets = array();
while (true) {
$subsets[] = array_intersect_key($set, array_flip($indexes));
$firstIndexToIncrease = $subsetsSize - 1;
for (; $firstIndexToIncrease >= 0; $firstIndexToIncrease--) {
$j = $subsetsSize - 1 - $firstIndexToIncrease;
if ($indexes[$firstIndexToIncrease] != $setSize - $j - 1) {
break;
}
}
if ($firstIndexToIncrease == -1) {
break;
}
$indexes[$firstIndexToIncrease]++;
for ($i = $firstIndexToIncrease + 1; $i < $subsetsSize; $i++) {
$indexes[$i] = $indexes[$i - 1] + 1;
}
}
return $subsets;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment