2010-06-22 144 views
2

我想隨機生成一個數組frm的數字,&每個數字都應該是唯一的,我給出了一段代碼。好心的幫助我,& plz dnt爲arraylist,bcoz建議爲黑莓應用程序,& blackberry api不支持arraylist或集合或哈希集,所以善意地建議我與數組只在代碼段。如何從java中的數組中隨機生成一個唯一的數字

Random rgen = new Random(); // Random number generator 

    //--- Initialize the array 
    for (int i=0; i<20; i++) { 
     quesNum[i] = i; 
    } 

// ---洗牌是每個元素交換隨機

for (int i=0; i< 20; i++) { 
     int randomPosition = rgen.nextInt(20); 

     int temp = quesNum[i]; 

     quesNum[i] = quesNum[randomPosition]; 

     quesNum[randomPosition] = temp; 


    } 
+0

你能解釋一下這段代碼在做什麼,你不想要的或者你想要的代碼不是什麼? – 2010-06-22 16:46:01

回答

4

您的代碼幾乎是好的,因爲它是,但你應該使用修改後的Fisher-Yates shuffle代替:

for (int i=0; i < 20; i++) { 
    // Partition the array into "shuffled" at the start 
    // and "unshuffled" at the end. Select a random 
    // unshuffled one, and swap it with the one at the 
    // border of shuffled/unshuffled 
    int randomPosition = i + rgen.nextInt(20 - i); 
    int temp = quesNum[i]; 
    quesNum[i] = quesNum[randomPosition]; 
    quesNum[randomPosition] = temp; 
} 

從你的問題來看,你真的不清楚你要求的是什麼 - 驗證你正在考慮正確的方向?如果這個答案對你沒有幫助,請澄清這個問題(理想情況下沒有文字縮寫)。