External Exam Download Resources Web Applications Games Recycle Bin

shuffle


imagine a deck with 3 cards (so elements 0, 1 and 2 of an array):
shuffling the bad way..

for each of the original cards[0] to cards[2]:
  choose a random card between cards[0] and cards[2]
  swap the original card with the random card

shuffling the better way..
for each of the original cards[2] counting down to cards[0]:
  choose a random card between cards[0] and the original card im currently at
  swap the original card with the random card

shuffle: java
import java.util.Random;
public class shuffle{
  public static void main(String[] args) {
    //*****SET UP 2 DECKS*****:
    int[] cardDeck = new int[52];
    int[] tempDeck = new int[52];
    for(int count=0; count<52; count++) {
      cardDeck[count] = count;
      tempDeck[count] = count;
    }
    
    //*****NOW SHUFFLE*****:
    Random seed = new Random(); 
    for(int number=52; number>=1; number--) {
      int numbersLeft = seed.nextInt(number);
      cardDeck[number-1] = tempDeck[numbersLeft];
      tempDeck[numbersLeft] = tempDeck[number-1];
    }
    
    //*****CHECK RESUT*****:
    for(int test=0; test<52; test++){
      System.out.println(cardDeck[test]);
    }
  }
}