Tuesday, October 2, 2012

Java: Random Unique Indexes

Say you have a list of items, you want to pick item from the list in random order, but need to avoid duplicate items until you get all items from the list.
assume below list of colors
0. Red
1. Blue
2. Yellow
3. Green

You may have to display as Blue, Red, Yellow and Green, here you see we have random items but not duplicated.

Here I write a Java Utilities for that purpose. Here we have to generate random numbers with in the limit but we have to ignore already generated values when try next time.

So, First create a list of indexes.

[0]->0
[1]->1
[2]->2
[3]->3


mIndexes = new int[size];
for(int i = 0 ; i < mIndexes.length;i++){
mIndexes[i] = i;
}
First you have to create a random number within the size so,
mNextMaxIndex = size;

Let see how to generate random index with no duplicate.
Generate a random index with the size limit.
int index = mRandom.nextInt(mNextMaxIndex);
Value from the index will be the result.
int result = mIndexes[index];
now swap this value to end of the effect list and reduce the limit by one.

mNextMaxIndex--;
mIndexes[index] = mIndexes[mNextMaxIndex];
mIndexes[mNextMaxIndex] = result;

Say you got 2 then result will be 2 and our new list will be

[0]->0
[1]->1
[2]->3
[3]->2
and mNextMaxIndex will be 3.
Now for the next index, generate a random number within 3 and do the same steps again.
But finally if we reach the start we have to reset back start from the end.

if(mNextMaxIndex<1 font="font">
mNextMaxIndex = mIndexes.length;
}

I have the source code here, it have a main method to test his also i see a







No comments: