Java – correct logic, select a card randomly from the card holder until all cards are selected

I need some advice here I want to create a logic that randomly selects one card from a deck of 52 cards until all cards are selected. If all 52 cards are used, I need to shuffle and start again

I've created a working logic for this, but I think there should be a better way to do it Some MMM - Master of mathematics ideas can end my pain

This is logic:

>Create an empty ArrayList to store all 52 cards for inspection > randomly select a card to check whether it exists in the ArrayList > If yes, repeat step 2 > if not, add the card to the ArrayList > if the 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);

The only problem with this logic is that when there is only one card left, the probability of randomly obtaining the card is less than 2% The system took a lot of time to find the card It continues to check the while while loop Please make suggestions for improvement and thank you for your time

Solution

One option is to start with a complete ArrayList containing all cards, and then delete the random index until the list is empty, at which time you will repopulate 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();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>