0

Let's say I have set = [1, 2, 3, 4, 5, 6, 7]

I'd like the following in return [1, 2, 3, 4, 5] [4, 3, 2, 1, 6] [7, 5, 1, 3, 2]..........

Essentially, as the title states I'm looking to generate specific sized combinations from an array but each combination can't have any duplicate items (so no aaab, aaac if you get the idea).

I've found another question here as well, but it had dupes within the combinations. I've tried tweaking and writing the recursive function to no avail :/

whisky
  • 533
  • 1
  • 6
  • 14
  • 1
    Could you please post some of your (relevant) code? – Bono Mar 02 '15 at 01:02
  • $set = array('A', 'B', 'C', D', 'E', 'F', 'G'); Just need combinations like ['A', 'B', 'C'] ['C', 'D', 'G'] etc.. – whisky Mar 02 '15 at 01:07
  • Can you post the code you've found... – Whirlwind Mar 02 '15 at 01:29
  • http://stackoverflow.com/questions/19067556/php-algorithm-to-generate-all-combinations-of-a-specific-size-from-a-single-set – whisky Mar 02 '15 at 01:33
  • Really, it's just generating all combinations of size x for a set of elements of size y with no dupes. – whisky Mar 02 '15 at 01:34
  • I understand, but I think this function does not make any duplicates...I just tested it ... Can you give me an inputs which you are using when getting duplicates? – Whirlwind Mar 02 '15 at 01:44

1 Answers1

5

Alright - all possible subsets without duplicates and assuming that the order does not matter, i.e. [1, 2, 3, 4, 5] is the same as [5, 4, 3, 2, 1]. Minimalistic example:

<?php
$arr = array(1, 2, 3, 4, 5, 6, 7);

function getSubsets($set, $items) {
  $result = array();
  getSubsets2($set, $items, 0, array(), $result);
  return $result;
}

function getSubsets2($set, $items, $index, $current, &$result) {
  if (sizeof($current) === $items) {
    $result[] = $current;
    return;
  }
  if ($index < sizeof($set)) {
    getSubsets2($set, $items, $index + 1, $current, $result);
    $current[] = $set[$index];
    getSubsets2($set, $items, $index + 1, $current, $result);
  }
}

$subsets = getSubsets($arr, 5);

echo(sizeof($subsets)); // 21
?>

Not to carry off someone else's laurels: This is 100% based on another Stack Overflow answer written in java.

Community
  • 1
  • 1
Marvin
  • 13,325
  • 3
  • 51
  • 57
  • I'm not looking for random per say. I'm looking for every, each and every possible 5 item combinations from that set of 7 (my example). Edit: I revised my question and title accordingly! – whisky Mar 02 '15 at 01:19
  • Beauty. You're a gem. – whisky Mar 02 '15 at 02:20