我正在尝试实现一种完美的洗牌方法,它将一副牌分成两部分,然后将牌交织在一起,这样你就可以将每副牌中的一张放入新牌中。当我尝试运行当前程序时,我得到的输出是:
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;
}
您正在 main 方法中的 for 循环中复制 value1 中的 0,然后将其传递给 PerfectShuffle
关于Java:使用数组洗牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858106/