tags:

views:

127

answers:

7

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();
    }
}
+2  A: 

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

Bill the Lizard
A: 

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

Aymen
+3  A: 

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.

Vladimir Dyuzhev
A: 
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.

seanizer
A: 

can anyone help me wid the code i mentioned above.the numbers generated should b unique & random too.

Arunabha Dutta Choudhury
A: 

wen i use collection.shuffle(quesNum),it says nt suuported,& gives error,i mean working in eclipse 3.4 ganymade

Arunabha Dutta Choudhury
Do you mean Collections.shuffle() is not supported on Blackberry? Then copy the code of Collections.shuffle(List,Random) into your application and use it. It's about 20 lines only.
Vladimir Dyuzhev
A: 

i m nt getting u,can u kindly write d exact code for it,will b grateful for ur kind help.

Arunabha Dutta Choudhury