Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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

like image 317
Hisham Muneer Avatar asked Nov 18 '25 15:11

Hisham Muneer


1 Answers

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();
like image 160
Alex - GlassEditor.com Avatar answered Nov 20 '25 05:11

Alex - GlassEditor.com



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!