So i'm making a game where i have to randomize 52 numbers from 1 to 52 so the order has to change i use this
class Deck
{
Random r = new Random();
int[] Card = new int[52];
}
you fill in the array from 1 to 52
for(int i=0;i<52;i++)Card[i]=i+1;
and then you shuffle it:
for(int i=1;i<52;i++){
int randIndex = r.nextInt(i+1);
int tmp = Card[i];
Card[i] = Card[randIndex];
Card[randIndex]=tmp;
}
Since you are building and shuffling a deck of cards I will point you to the java 1.5 Enum tutorial. It uses enum
s to build up a Collection of cards and then uses Collections.shuffle()
to randomize the deck.
public class Card {
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Rank rank() { return rank; }
public Suit suit() { return suit; }
public String toString() { return rank + " of " + suit; }
private static final List<Card> protoDeck = new ArrayList<Card>();
// Initialize prototype deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
protoDeck.add(new Card(rank, suit));
}
public static ArrayList<Card> newDeck() {
return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
}
}
This builds your deck. The following then shuffles with Collections.shuffle()
and deals some cards.
public class Deal {
public static void main(String args[]) {
int numHands = Integer.parseInt(args[0]);
int cardsPerHand = Integer.parseInt(args[1]);
List<Card> deck = Card.newDeck();
Collections.shuffle(deck);
for (int i=0; i < numHands; i++)
System.out.println(deal(deck, cardsPerHand));
}
public static ArrayList<Card> deal(List<Card> deck, int n) {
int deckSize = deck.size();
List<Card> handView = deck.subList(deckSize-n, deckSize);
ArrayList<Card> hand = new ArrayList<Card>(handView);
handView.clear();
return hand;
}
}