Correct logic to randomly select a card from deck until all cards are selected

java, logic, math, random

Solution

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();

Problem

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: - Create an empty arraylist to store the all 52 cards for checking - Select a card randomly and check if that exist in the arraylist - if yes, repeat step 2 - if no, add the card to arraylist 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.

Original source

Related problems