簡體   English   中英

Java:使用數組在卡組中洗牌

[英]Java: Shuffling Cards in a Deck using Arrays

我正在嘗試實現一種完美的隨機播放方法,它將一個卡座分成2個,然后將這些卡交織在一起,以便每個卡座中的一個被放置到新卡座中。 當我嘗試運行當前程序時,我得到的輸出是:

Results of 3 consecutive perfect shuffles:
   1: 0 4 1 5 2 6 3
   2: 0 2 4 6 1 3 5
   3: 0 1 2 3 4 5 6

我不明白為什么每次洗牌時都會得到0作為我的第一個值。 誰能告訴我我做錯了什么? 這是我的代碼:

class Ideone {
/**
 * The number of consecutive shuffle steps to be performed in each call
 * to each sorting procedure.
 */
private static final int SHUFFLE_COUNT = 3;

/**
 * The number of values to shuffle.
 */
private static final int VALUE_COUNT = 7;

/**
 * Tests shuffling methods.
 * @param args is not used.
 */
public static void main(String[] args) {
    System.out.println("Results of " + SHUFFLE_COUNT +
                             " consecutive perfect shuffles:");
    int[] values1 = new int[VALUE_COUNT];
    for (int i = 0; i < values1.length; i++) {
        values1[i] = i;
        }
    for (int j = 1; j <= SHUFFLE_COUNT; j++) {
        perfectShuffle(values1);
        System.out.print("  " + j + ":");
        for (int k = 0; k < values1.length; k++) {
            System.out.print(" " + values1[k]);
        }
        System.out.println();
    }
    System.out.println();
}
   public static void perfectShuffle(int[] values) {
    int[] temp = new int[values.length];
    int halfway = (values.length +1)/2;
    int position = 0;

    for (int j = 0 ; j < halfway; j++)
    {
        temp[position] = values[j];   
        position +=2;
    }

    position = 1; 
    for (int k = halfway; k < values.length; k++)
    {
        temp[position] = values[k];
        position +=2;
    }

    for (int k = 0; k < values.length; k++)
        values[k] = temp[k];
    } 
}

數組索引從0而不是1開始。

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

您正在主要方法中的此for循環的values1中復制0,然后將其傳遞給perfectShuffle

您先從0開始填充“牌組”,然后隨機播放,但是隨機播放始終將“ 0”卡放在第一位,這樣它就不會真正被隨機插入。使用#1可以看到以下內容:

    for (int i = 1; i < values1.length+1; i++) {
        values1[i-1] = i;
    }

同樣,使用偶數張卡時,您的最后一張卡也不會更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM