Java:使用数组在甲板上洗牌

时间:2016-03-08 02:58:31

标签: java arrays shuffle

我正在尝试实施一种Perfect Shuffle方法,它将甲板分成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];
    } 
}

2 个答案:

答案 0 :(得分:0)

数组索引从0开始而不是1.

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

你在main方法的for循环中的values1中复制0,然后传递给perfectShuffle

答案 1 :(得分:0)

你从“0”开始填充“牌组”然后随机播放,但是你的随机播放总是首先放入“0”牌,所以它永远不会真正被洗牌。你可以用#1看到同样的事情:

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

此外,使用偶数张卡,您的最后一张卡也不会改变。

相关问题