whisky
whisky

Reputation: 533

Every (specific sized) combination from set/array with no duplicate items

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

Upvotes: 0

Views: 459

Answers (1)

Marvin
Marvin

Reputation: 14255

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.

Upvotes: 5

Related Questions