we should fill the array with the values in order. we should go through the array and exchange each element with the randomly chosen element in the range.
Shuffling a deck of cards
// Java Code for 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]+" ");
}
}
Here’s an example of what the output might look like after shuffling the deck:
12 6 23 48 25 18 8 3 42 35 22 50 30 7 5 19 27 4 11 41 28 47 26 45 14 38 40 16 29 24 21 46 13 2 36 43 10 31 49 32 33 39 44 15 1 34 37 9 20 17 0 51