Reputation: 1047
I want to implement a poker game in Java. So I made a card class and created 52 card objects and put them into a array. This array is the card deck.
How would I randomly shuffle this array of objects? Is there an inbuilt method or any other way?
Upvotes: 4
Views: 5856
Reputation: 26742
I've modified the top answer from "Random shuffling of an array" to work for an array of Card
objects. I simply changed int[] ar
→ Card[] ar
, and int a = ar[index]
→ Card a = ar[index]
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
// Implementing Fisher–Yates shuffle
static void shuffleArray(Card[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
Card a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
Upvotes: 1
Reputation: 1270
Collections.shuffle isn't good enough:
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood. The hedge "approximately" is used in the foregoing description because default source of randomness is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm would choose permutations with perfect uniformity.
You need a source of randomness producing a number that is exactly distributed uniformly between 1 and 52! (inclusive).
Upvotes: 0
Reputation: 240860
Use ArrayList
instead and use Collections.shuffle()
Collections.shuffle(yourListInstance);
Upvotes: 6