Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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;
- }
- }
Add Comment
Please, Sign In to add comment