2014-12-01 50 views
1

數組這是我迄今爲止錯誤而洗牌在Java中

int[] question = new int[25]; 

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

Random rand = new Random(); 

int max = question.length-1, min = 1; 

for(int i = 0; i < question.length; i++){ 
    int idx = rand.nextInt((max - min) + 1) + min; 
    randg[i] = idx; 
    question[i] ^= question[idx]; 
    question[idx] ^= question[i]; 
    question[i] ^= question[idx]; 

    if(question[i] == 0){ 
     System.out.println("Something went wrong!" + i + " " + idx); 
    } 
} 

所以,問題似乎是當蘭特值(IDX)等於我,爲交換......它只是用0替換該值。

如何解決該問題?

+0

如果無法到告訴錯誤的影響是什麼,然後很難提供幫助。 – AlexWien 2014-12-01 20:40:05

+0

我知道問題是什麼......我只是不知道如何解決它。 – 2014-12-01 20:40:23

+0

問題是,它交換的idx值等於i值。它將該值設置爲零。 – 2014-12-01 20:41:08

回答

3

我知道最快的修復方法;使用Integer[]Arrays.asList(T...)Collections.shuffle(List)

Integer[] question = new Integer[25]; 
for (int i = 0; i < question.length; i++) { 
    question[i] = i + 1; 
} 
System.out.println(Arrays.toString(question)); 
Collections.shuffle(Arrays.asList(question)); 
System.out.println(Arrays.toString(question)); 

,或者用代碼,你可以添加

for(int i = 0; i < question.length; i++){ 
    int idx = rand.nextInt((max - min) + 1) + min; 
    if (idx == i) { 
    i--; 
    continue; 
    } 
+0

我需要的方法返回一個'int []' – 2014-12-01 20:43:11

+3

@Arian你可以將它複製到一個'int []' – 2014-12-01 20:44:02

+0

但是這並不回答他爲什麼得到一個0. – AlexWien 2014-12-01 21:05:12

1

不建議將您正在使用的XOR交換,它可以零出位, 你的時候通過相同的變量兩次,所以交換(a,a)可能會提供0: 更多信息請參閱:https://softwareengineering.stackexchange.com/questions/182037/is-this-xor-value-swap-algorithm-still-in-use-or-useful

你沒有得到XOR Swap,它既不聰明也不fa韋伯斯特。 這是彙編langugae保存一個變量的技巧。

的推薦方法來交換:

在陣列交換兩個值的[]索引i和j:A [1]和a [j]的:

int help = a[i]; 
a[i] = a[j]; 
a[j] = help; 
+1

OP是使用xor swap算法,它不需要一個臨時的。 – 2014-12-01 20:47:13

+0

@ElliottFrisch如果使用相同的參數,XOR交換可能會將位清零(http://programmers.stackexchange.com/questions/182037/is-this-xor-value-swap-algorithm-still-in-use-or-有用 – AlexWien 2014-12-01 20:58:39