繁体   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