2

Tried to create a random method that would query the database, obtain the number of rows in the database, and then grab a random number between 1 and the total number of rows to fetch a specific item in the database. It works alright, but not great, if there are less than ten entries in the database it will repeat the same entry about 4 out of ten times. I think I need a lead on a better method.

 number = mDbHelper.getCount(mDbHelper.mDb);
 Random generator = new Random(); 
 n = generator.nextInt((int) number);
 if(n <= 1){
   n = 1;
 }

Any ideas?

Will
  • 147
  • 3
  • 11

2 Answers2

4

Based on your description, your database query is 1's-based. Java nextInt is 0's-based, that is, .nextInt(10) will generate a random number between 0 and 9. So your proper solution is to change line 3 to

n = generator.nextInt((int) number) + 1;

this will then give you what you need.

Because at present you are converting both [0] and [1] into 1 in lines 4 & 5, you are skewing your probability distribution. Your first entry is going to get counted twice. If you have an average of 5 entries in your database, this would give you the 2/5 = 40% hit rate you're seeing.

Hussain
  • 5,552
  • 4
  • 40
  • 50
DragonLord
  • 6,395
  • 4
  • 36
  • 38
2

First, I would try moving the line:

Random generator = new Random();

To your class's constructor or some other place where it will only get created once. That should definitely help.

Other than that, the answers to this question might help you out: How good is java.util.Random?

Community
  • 1
  • 1
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • I do have the random function in the class constructor. I am looking over the answer the you posts, there is a lot of information in there. – Will Oct 03 '10 at 18:49