简体   繁体   中英

How to get distinct different random objects in an array?

Sorry if this is long but i'm writing a program that draws a poker hand(5 different cards) from a standard deck of 52. The only part Im still struggling with is getting different cards. The code I have now is as simple as it gets and works for the most part but sometimes can draw the same card more than once. I want the card to be removed from the deck once its drawn and i'm stuck on that part.

Card[] hand = new Card[5];
        for (int i = 0; i < 5; i += 1)
        {
          int index = rand.nextInt(52);
          hand[i] = cards[index];
        }
    return hand;

Use List and Collections.shuffle().

List<Card> cards = new ArrayList<>(52);
for (int i = 0; i < 52; i++) {
  cards.add(new Card(i)); // or so
}
Collections.shuffle(cards);

Card[] hand = new Card[5];
for (int i = 0; i < 5; i += 1) {
  hand[i] = cards.remove(0);
}

return hand;

You can create a ArrayList like

List<Card> cards = new ArrayList<>();

// add 52 cards to cards

Card[] hand = new Card[5];
for (int i = 0; i < 5; i ++) {
    int index = rand.nextInt(cards.size());
    hand[i] = cards.remove(index);
}

You could literally do what you do with a deck of cards:

class Deck
{
    private LinkedList<Card> cards = new LinkedList<Card>();

    Deck()
    {
          for (i=0; i<52; ++i) {
              // or however you want to correctly create a card
              cards.add(new Card(i))
          }
    }

    public Card takeRandomCard()
    {
          int takeCard = rand.nextInt(cards.size());
          return cards.remove(takeCard);
    }
}

int handSize = 5;
Deck deck = new Deck();
Card[] hand = new Card[handSize];
for (int i=0; i<handSize; ++i) {
    hand[i] = deck.takeRandomCard();
}

This may not be the most efficient method but it's hopefully pretty clear what it's doing.

Pulling random cards may or may not be faster than shuffling the entire deck first. LinkedList is faster than ArrayList when removing random entries. Probably irrelevant though really.

Just create a List of Integer s ranging from 1 to 50. I've demonstrated this example using Java 1.8 .

public class NumUtility {
    public static List<Integer> shuffle() {
        List<Integer> range = IntStream.range(1, 53).boxed()
                .collect(Collectors.toCollection(ArrayList::new));
        Collections.shuffle(range);
        return range;
    }
}

Now you can iterate through index 1 to 5 and whenever you want shuffled numbers, just call the above method.

Card[] hand = new Card[5];

//call this method whereever you want random integers.
List<Integer> range = NumUtility.shuffle();

for (int i = 0; i < 5; i += 1) {
    hand[i] = range.get(i);
}
return hand;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM