簡體   English   中英

如何獲得數組中不同的隨機對象?

[英]How to get distinct different random objects in an array?

抱歉,如果這很長,但是我正在編寫一個程序,可以從52張標准牌中抽出一張撲克手(5張不同的紙牌)。Im仍在掙扎的唯一部分是獲得不同的紙牌。 我現在擁有的代碼就很簡單,並且大部分都能正常工作,但有時可以多次繪制同一張卡。 我希望將卡抽出后從卡組中取出,然后卡在那部分上。

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

使用List和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;

您可以創建一個ArrayList像

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);
}

您實際上可以使用一副紙牌來做:

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();
}

這可能不是最有效的方法,但希望可以很清楚地知道它在做什么。

拉隨機卡的速度可能快於或可能不快於先隨機播放整個牌組。 刪除隨機條目時,LinkedList比ArrayList快。 可能實際上無關緊要。

只需創建一個范圍為1到50的Integer List 。我已經使用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;
    }
}

現在,您可以遍歷索引1到5,並且每當您想要改組數字時,只需調用上述方法即可。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM