2010-06-22 142 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; 
} 

从你的问题来看,你真的不清楚你要求的是什么 - 验证你正在考虑正确的方向?如果这个答案对你没有帮助,请澄清这个问题(理想情况下没有文字缩写)。