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 :/

6
  • 1
    Could you please post some of your (relevant) code? Commented Mar 2, 2015 at 1:02
  • $set = array('A', 'B', 'C', D', 'E', 'F', 'G'); Just need combinations like ['A', 'B', 'C'] ['C', 'D', 'G'] etc.. Commented Mar 2, 2015 at 1:07
  • Can you post the code you've found... Commented Mar 2, 2015 at 1:29
  • stackoverflow.com/questions/19067556/… Commented Mar 2, 2015 at 1:33
  • Really, it's just generating all combinations of size x for a set of elements of size y with no dupes. Commented Mar 2, 2015 at 1:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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!
Beauty. You're a gem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.