洗牌机算法

时间:2013-05-11 18:36:15

标签: java

我有以下java代码,它应该在一个套牌中“洗牌”。套牌是包含卡片对象的arraylist。

private void ShuffleDeck() {
    //Number of cards in deck
    int deckSize = deck.size();

    //Swapping 100 cards
    for(int i = 0; i < 15; i++) {

        //Generating two random card indexes
        int indexA = (int) ((Math.random() * deckSize-1));
        int indexB = (int) (Math.random() * deckSize-1);
        System.out.println(indexA + " " + indexB);

        //Getting objects
        Card cardA = deck.get(indexA);
        Card cardB = deck.get(indexB);

        //Temporaily removing these cards from deck
        deck.remove(cardA);
        deck.remove(cardB);

        //Swapping around the two cards
        deck.add(indexA, cardB);
        deck.add(indexB, cardA);

    }

}

然而,当我运行这种方法时,一些卡片似乎从卡座上“消失”......有什么建议为什么会这样? :)

1 个答案:

答案 0 :(得分:9)

假设deckList<Card>(包括ArrayList等):

public void shuffleDeck() { // please use camelCase method names
    Collections.shuffle(deck);
}

不要重新发明轮子。