我想實現一個完美洗牌方法,它將一個甲板分成2個,然後交織這些牌,以便每個甲板都有一個放入新的甲板。當我嘗試運行我目前的程序,輸出我會得到的是:Java:使用陣列在甲板上洗牌
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作爲我的每個I洗牌時間第一個值。誰能告訴我我做錯了什麼?這是我的代碼:
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];
}
}