简体   繁体   English

Java:洗牌32张牌?

[英]Java: Shuffle a Deck of 32 cards?

I've wrote this method on my own I want to know if there is a better way to do it? 我自己写了这个方法我想知道是否有更好的方法来做到这一点?

public Card[] shuffle(){
    for(int i = 0; i < Deck.length; i++){
       int x = i + (int) (Math.random() * (32 - i));
       Card temp = Deck[i];
       Deck[i] = Deck[x];
       Deck[x] = temp;
    }
    return Deck;
}

You not checking, if ( 32 - i ) ever gives any value less than 0 . 你不检查,如果( 32 - i )给出任何小于0值。 The algorithm is called Fisher-Yates shuffling algorithm, which resemble very much like yours: 该算法称为Fisher-Yates混洗算法,与您的非常相似:

private int [] shuffleMyArray ( int [] array ) {
    int size = array.length, i = 0;
    int temp = 0;
    while ( size != 0 ) {
        i = ( ( int ) ( Math.random () * size-- ) );
        if ( i < 0 ) {
            i = 0;
        }
        temp = array [ size ];
        array [ size ] = array [ i ];
        array [ i ] = temp;
    }
    return array;
}

EDIT 1: 编辑1:

The output of both the algorithms will better make you understand the difference between the two, see how Fisher-Yates take all indices into account, while shuffling. 这两种算法的输出将更好地让你理解两者之间的差异,看看Fisher-Yates如何考虑所有指数,同时改组。

OUTPUT: OUTPUT:

Actual Array
0 1 2 3 4 
Your Implementation output
i: 0 x: 3
i: 1 x: 4
i: 2 x: 3
i: 3 x: 4
i: 4 x: 4
Fisher Yates implementation output
i: 4 size: 4
i: 2 size: 3
i: 1 size: 2
i: 0 size: 1
i: 0 size: 0

I'm going to make the deck an argument, and the method static . 我要让deck成为一个参数,而方法是static That way it's self contained. 这样它就是自包含的。 In Java, naming conventions are to make variables and method names start with a lower case letter. 在Java中,命名约定是使变量和方法名称以小写字母开头。 Next, the shortest way I know is to shuffle the deck in place with Collections.shuffle(List) and Arrays.asList(T...) like 接下来,我知道的最简单的方法是使用Collections.shuffle(List)Arrays.asList(T...)

public static void shuffle(Card[] deck) {
    Collections.shuffle(Arrays.asList(deck));
}

If you want to preserve the original deck , then you could copy it and return like 如果你想保留原始deck ,那么你可以复制它并return

public static Card[] shuffle(Card[] deck) {
    List<Card> al = new ArrayList<>(Arrays.asList(deck));
    Collections.shuffle(al);
    return al.toArray(new Card[deck.length]);
}

I guess you can get a better result if you choose the item to be exchanged from the whole deck and not only from the remaining cards, like this: 如果你从整个套牌中选择要交换的项目而不仅仅是剩余的卡片,我想你可以得到更好的结果,如下所示:

public Card[] Shuffle(){
    for(int i = 0; i < Deck.length; i++){
       int x = (int) (Math.random() * 32);
       Card temp = Deck[i];
       Deck[i] = Deck[x];
       Deck[x] = temp;
    }
    return Deck;
}

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

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