Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all possible combinations given this criteria?

I have an array of Card instances.

Card[] allCards;

I am supposed to get all the possible combinations of these cards, under the following conditions:

  • All of the combinations must have a minimum of 3 cards.
  • A combination has no card limit (so if there are a total of 15 cards, you know there can be a combination of 15 cards, others of 13, 10, etc).

For college purposes, I am not supposed to use any fancy library capable of doing this job easier.

I've done it with pairs, sure, but considering that there is no limit, the algorithm I would usually do would not work.

It is pretty much what they ask here for python: Find all possible combinations

Any ideas? I don't want code or anything - I'm just lost with the algorithm/idea.

My Problem (more detailed)

I can make pairs by making two loops (one within the other). I can make triplets by having three loops (one within another within another).

But I don't know how to do this specific problem because:

  • What if the array has 15 cards? I can't write 15 loops...
  • And then of course I need to go down to 14, 13, 12 loops... (because all the combinations are not of 15 elements each, there can be combinations of 14, 13, 12 elements when working with this 15-elements-array)

I can find some combinations, but not dynamically.

like image 768
Voldemort Avatar asked Nov 12 '22 18:11

Voldemort


1 Answers

Paper and Pencil exercise:

Let's back away from the Java syntax for a minute. Take an example of 5 cards, say the Ace through 10 of diamonds. Now list out every possible pair. (Hint: there are 10 of them)

Now using your list of pairs, list every possible triple.

Now using the list of triples, list every possible combination of 4.

Now let's code it:

Since you don't know the maximum length of a combination at compile time, using loops will not solve the problem. On the other hand, this problem lends itself to recursion. Let's start by assuming that we have a function Card[][] getCombinations(Card[] cards) which returns an array of arrays of Cards. So if we call

Card[] cards = new Card[15];
// initialize individual Card objects
Card[][] combinations = getCombinations(cards);

combinations[i] contains one of the combinations generated.

Now, to make things easy, let's say that getCombinations() only returns pairs. How can you use these pairs to create all possible triples?

like image 110
Code-Apprentice Avatar answered Nov 15 '22 12:11

Code-Apprentice