what is the most efficient way to pick a random card from a deck when some cards are unusable?
问题 I have an array which tells whether a card is in use: int used[52]; This is a terrible way to pick a random card if I have many used cards: do { card = rand() % 52; } while (used[card]); since if I have only 3-4 unused cards, it'll take forever to find them. I came up with this: int card; int k = 0; int numUsed = 0; for (k=0; k < 52; ++k) { if (used[k]) numUsed += 1; } if (numUsed == 52) return -1; card = rand() % (52 - numUsed); for (k=0; k < 52; ++k) { if (used[k]) continue; if (card == 0)