简体   繁体   English

随机从纸牌中获得一次 select 对象

[英]Randomly select objects once from deck of cards

I pretty sure my remainder operator is in the wrong place, I've tried a few different variations, program still runs but pulls the same card more than once:我很确定我的余数运算符在错误的位置,我尝试了一些不同的变体,程序仍然运行但不止一次拉同一张卡:

Card [] deck = {card0, card1, card2, card3, card4, card5, card6, card7, card8, card9, card10, card11, card12, card13,
        card14, card15, card16, card17, card18, card19, card20, card21, card22, card23, card24, card25, card26, card27, card28,
            card29, card30, card31, card32, card33, card34, card35, card36, card37, card38, card39, card40, card41, card42, card43,
            card44, card45, card46, card47, card48, card49, card50, card51,
        };
for (int i = 0; i<deck.length;i++){
    deck[i] = deck[i%51];
    }
for (int i = 0; i<deck.length; i++){
    index = (int)(Math.random()*deck.length);
    deck[index] = deck[i];

    System.out.println(deck[i] + " ");

    }

I know the deck isn't created in the most efficient manner, that's due to limitations of the assignment.我知道套牌不是以最有效的方式创建的,这是由于任务的限制。 I've only included a small piece of the code, because I think the issue is with my for loop and remainder operator.我只包含了一小部分代码,因为我认为问题出在我的 for 循环和余数运算符上。

The trick is to randomly shuffle the deck and then output it in the shuffled order.诀窍是随机洗牌,然后按洗牌顺序 output 它。

Have a look at Collections.shuffle .看看Collections.shuffle

Not sure what are you trying to do here, since i%51 is always equal to i in this case:不知道你想在这里做什么,因为在这种情况下i%51总是等于i

for (int i = 0; i<deck.length;i++){
    deck[i] = deck[i%51];
    }

Now to generate a random number between 0 and 50, you need something like现在要生成 0 到 50 之间的随机数,您需要类似

int randomInt = (int)(50.0 * Math.random());

Thus you should use:因此,您应该使用:

for (int i = 0; i<deck.length; i++){
    index = (int)((deck.length-1) * Math.random());
    System.out.println(deck[index] + " ");
    }

But be sure that, some duplicates you may see using this method.但请确保,使用此方法可能会看到一些重复项。 If you want each card to be drawn/displayed only once, then use Collections.shufffle(..)如果您希望每张卡片仅绘制/显示一次,请使用Collections.shufffle(..)

List<Card> deckList = Arrays.asList(deck);
Collections.shuffle(deckList);
for(Card card : deckList){
  System.out.println(card);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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