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:
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:
I can find some combinations, but not dynamically.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With