I need some advice here. I want to create a logic to randomly select one card at a time from a deck of 52 cards until all cards are selected, if all 52 cards are used, i need to reshuffle the deck and start again.
I already created a logic for this which is working fine, but I think there should be some better way to do this. Some MMM - Maths Master Minds can end my misery.
Here is the logic:
if arraylist size is 52, empty the arraylist
ArrayList<Integer> list = new ArrayList<Integer>();
int card = -1;
do {
Random random = new Random();
card = random.nextInt(52);
} while (list.contains(card) == true);
// code for drawing the card by the number
list.add(card);
Only problem with this logic is when there is only one card left, there is less than 2% chances of getting that card by random. System is spending a lot of time to find the card. It keep checking that do while loop.
Please suggest improvements and thanks for your time.
One option would be to instead start with a full arraylist containing all the cards and then remove a random index until the list is empty, at which time you would refill it.
Example:
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<52;i++){
list.add(i+1);
}
int c = 52;
Random random = new Random();
while(c>0){
int r = random.nextInt(c--);
int card = list.get(r);
list.remove(r);
}
resetList();
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