I have just had a brain block, I have a Deck object and want to get every 5 card combination from it in a iterative manner. Could someone show me h开发者_JAVA百科ow to do this, I would imagine it would be:
for(int i =0; i <52; i++){
for(int j = i + 1 ; j < 52; j++){
for(int k = j + 1; k < 52; k++{
for(int l = k + 1; l < 52; l++){
for(int m = l + 1; m < 52; m++){
}
}
}
}
}
Is this correct?
Thanks
Yes, that works fine. If you want to enumerate all n-card combinations, this doesn't work.
For that, you'd need recursion. Put card 0 in slot 0. Recursively enumerate all n-1 card hands (excluding 0) in the remaining n-1 slots. Repeat, with card 1 in slot 0. Pretty easy.
EDIT: some code:
private static final int NUM_CARDS = 52;
public static void main(String[] args) {
enumerateAllHands(Integer.parseInt(args[0]));
}
private static void enumerateAllHands(int n) {
if (n > NUM_CARDS) {
throw new IllegalArgumentException();
}
int[] cards = new int[n];
BitSet cardsUsed = new BitSet();
enumerate(cards, 0, cardsUsed);
}
private static void enumerate(int[] cards, int from, BitSet cardsUsed) {
if (from == cards.length) {
emit(cards);
} else {
for (int i = 0; i < NUM_CARDS; i++) {
if (!cardsUsed.get(i)) {
cards[from] = i;
cardsUsed.set(i);
enumerate(cards, from + 1, cardsUsed);
cardsUsed.clear(i);
}
}
}
}
private static void emit(int[] cards) {
System.out.println(Arrays.toString(cards));
}
精彩评论