Shuffling a deck of cards, redundancy after replacing two values

I was asked to write a program (mainly a method) for shuffling a deck of cards. I wrote the following program:

public class Deck {

////////////////////////////////////////
// Data Members
////////////////////////////////////////

private Card[] cards; // array holding all 52 cards
private int cardsInDeck; // the current number of cards in the deck

public static final int DECK_SIZE = 52;

/**
 * Shuffles the deck (i.e. randomly reorders the cards in the deck). 
 */
public void shuffle() {
    int newI;
    Card temp;
    Random randIndex = new Random();

    for (int i = 0; i < cardsInDeck; i++) {

        // pick a random index between 0 and cardsInDeck - 1
        newI = randIndex.nextInt(cardsInDeck);

        // swap cards[i] and cards[newI]
        temp = cards[i];
        cards[i] = cards[newI];
        cards[newI] = temp;
    }
}

}

But in the above shuffling method, there is a logical error, which is as follows: suppose I replace card number 4 with card number 42, then I change twice. I am wondering if there is a way not to do this?

I checked one post here: Shuffling a deck of cards

But for me it didnโ€™t make sense.

+5
source share
3 answers

I am wondering if there is a way not to do this?

That's right. Instead of changing one card with any other, just replace one card with a later one.

, , i " ", . . , , , , .

-.

( , x [0, x]. , , . , , .)

, List<Card>, Collections.shuffle .

+15

Collections.shuffle, , src

  // Shuffle array
  for (int i=size; i > 1; i--)
      swap(arr, i-1, rnd.nextInt(i));

...

   private static void swap(Object[] arr, int i, int j) {
        Object tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
+7

- . , , Shuffle Fisher-Yates , .

( ). , , , .

. , , 1 9 .


(unshuffled) list {1,2,3,4,5,6,7,8,9} ( 9, ) ( 0 8 , , , Java). , , 4.

4 ( 5) _last (9) , . {1,2,3,4,9,6,7,8} 8.

, , ( 0 7 ). 1.

1 2, , , {1,8,3,4,9,6,7} 7.

, , 7, 4. 9, , {1,8,3,4,7,6} 6.

You must be able to see how this develops. Without any worries about sorting the entire list ahead, you can get a random sequence (well, as happens in random order, as the random number generator allows) without repetition.

+5
source

All Articles