Shuffle Deck of Cards Java

PROGRAM TO SHUFFLE A DECK OF CARDS


import java.util.Random;
  
class GFG {
      
    // Function which shuffle and print the array
    public static void shuffle(int card[], int n)
    {
          
        Random rand = new Random();
          
        for (int i = 0; i < n; i++)
        {
            // Random for remaining positions.
            int r = i + rand.nextInt(52 - i);
              
             //swapping the elements
             int temp = card[r];
             card[r] = card[i];
             card[i] = temp;
               
        }
    }
       
    // Driver code
    public static void main(String[] args) 
    {
        // Array from 0 to 51
        int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8,
                   9, 10, 11, 12, 13, 14, 15,
                   16, 17, 18, 19, 20, 21, 22,
                   23, 24, 25, 26, 27, 28, 29,
                   30, 31, 32, 33, 34, 35, 36,
                   37, 38, 39, 40, 41, 42, 43,
                   44, 45, 46, 47, 48, 49, 50
                   51};
       
        shuffle(a, 52);
       
        // Printing all shuffled elements of cards
        for (int i = 0; i < 52; i ++)
           System.out.print(a[i]+" ");
          
    }
}

OUTPUT
29 27 20 23 26 21 35 51 15 18 46 32 33 19 
24 30 3 45 40 34 16 11 36 50 17 10 7 5 4 
39 6 47 38 28 13 44 49 1 8 42 43 48 0 12 
37 41 25 2 31 14 22

Note : Output will be different each time because of the random function used in the program.

Comments

Popular posts from this blog

Solve the Sudoku Python

Solve the Sudoku Java

Find Duplicates Java