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.


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.

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

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

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

1 comment:

mary Brown said...

Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.