0

Code

Random Randomizer = new Random () ;
  cardoneA = suits[Randomizer.nextInt(suits.length)];
  cardoneAv = ranks[Randomizer.nextInt(ranks.length)];

How can I stop the Randomizer from picking the same cards twice? Eg. If it picks a certain suit and rank, how can I stop it from picking it again? Also, how can I make it pick those two together, so that it can pick another card of the same value, as long as its a different class?

4

4 回答 4

5

只需像在现实生活中那样模拟一副纸牌:

  1. 将所有尚未绘制的卡片存储在 ArrayList 中。
  2. 生成一个介于 0 和 ArrayList 的当前大小之间的随机数
  3. 取出被选中的卡片。现在数组的大小减少了一个。

该算法也称为Fisher-Yates Shuffle

于 2012-09-19T01:33:59.320 回答
2

You can't prevent the randomizer from returning the same index multiple times. You'll need to keep a list of which cards - a combination of suit index and rank index - have already been chosen, and pick new random indices in a loop, looping until you get a card that you haven't already picked.

于 2012-09-19T01:30:33.757 回答
2

与其跟踪您选择的卡片,不如跟踪您尚未选择的卡片,并在您尚未选择的卡片中随机选择数字。

  1. 用所有可能的组合初始化一个列表
  2. 生成一个 0 到(未选择的卡片数量 - 1)之间的随机数
  3. 选择卡片并从列表中删除卡片
  4. 重复第 2 步和第 3 步,直到您拥有所需数量的卡片,或已选择所有卡片。
于 2012-09-19T01:33:30.710 回答
1

你想洗牌吗?

list.add(list.remove(n));如果是这样,其中 n 是从 0 到 的随机数的单行语句list.size() - 1。重复此操作约 500 次,以获得体面的洗牌。这是一个常见的洗牌;随机取出一张卡片,放在上面。

于 2012-09-19T01:43:41.773 回答