Last active
February 9, 2016 16:41
-
-
Save nicmart/27ba1ceb7a7446820947 to your computer and use it in GitHub Desktop.
Enumerate all the subsets of a set of a given size
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 | |
/** | |
* @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