2016-03-08 68 views
1

我想实现一个完美洗牌方法,它将一个甲板分成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]; 
    } 
} 

回答

0

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

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

您在值1,在本作中你的主要方法循环通过它来传递给perfectShuffle

复制0
0

您可以从0开始填充“deck”,然后随机播放,但您的随机播放总是先放置“0”卡片,这样它就不会真正被拖入。您可以使用#1看到相同的内容:

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

此外,如果卡数偶数,则最后一张卡永远不会改变。