开发者

How to generate numbers from an array randomly,with each number being unique

开发者 https://www.devze.com 2023-01-04 05:30 出处:网络
I hav a numeric array,which contains 20 elements.I am displaying the numbers randomly for a blackberry application,bt i want dat all d numbers generated should b unique.It should b randomly generated,

I hav a numeric array,which contains 20 elements.I am displaying the numbers randomly for a blackberry application,bt i want dat all d numbers generated should b unique.It should b randomly generated,bt it has b unique until all the elemnts in the array is exhausted.I am giving the piece of code here,if anyone can help me out,i will开发者_开发技巧 b extremely grateful.

static int quesNum[] = new int[20];
static int quesCount = -1;

private static void initialize(){

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

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

    //--- Shuffle by exchanging each element randomly
    for (int i=0; i< quesNum.length; i++) {
        int randomPosition = rgen.nextInt(quesNum.length);

        int temp = quesNum[i];

        quesNum[i] = quesNum[randomPosition];

        quesNum[randomPosition] = temp;

    }
}

/*Changed the code to get a unique random number

*/
public static int getQuestionNumber() {
    quesCount++;
    if(quesCount < quesNum.length){
        return quesNum[quesCount];
     }
    else{ 
       initialize();
       quesCount = -1;
       return getQuestionNumber();
    }
}


Shuffle first, then iterate:

Collections.shuffle(listOfValues);
for(Integer val : listOfValues) {
  // give it to user
}

UPDATE

Some wording of OP makes me think Collections.shuffle() is not supported on Blackberry. Then advise is to copy the code of Collections.shuffle(List,Random) into the application.


What you're describing is a perfect application for just shuffling the array.


int len = 20;
Integer[] arr = new Integer[len];
for(int i =0;i<len;i++){
    arr[i] = Integer.valueOf(i+1);
}
Collections.shuffle(Arrays.asList(arr));

Now the array is shuffled and you can iterate over it.


You can use an ArrayList instead of the Array and delete each generated number.

0

精彩评论

暂无评论...
验证码 换一张
取 消