开发者

How to get a random range of 10 records from a database without overlapping the end boundary?

开发者 https://www.devze.com 2023-01-23 00:10 出处:网络
I need to get a List of 10 consecutive database records from a random offset in the database each time.

I need to get a List of 10 consecutive database records from a random offset in the database each time.

The problem I see with this is overlapping the end boundary.

For example:

Let's say my database only contains 20 records.

If I choose a random offset between 1 and 20 to start my read of 10 consecutive records and the random number happens to be, say, 15 - then I only get 开发者_高级运维5 records before I run into the end of the available range.

public getNext10RandomRecords() {

  int totalRecs = this.getTotalDatabaseRecordCount();
  Random rand = new Random();
  // ??
  int startOffSet = 15;
  int endOffSet = 25;
  query.setRange(startOffSet, endOffset); // oops! totalRecs == 20!

}


Choose your random offset to be in the range of 0 to totalRecs - 10. That way, the highest start offset will be totalRecs - 10 in which case your end offset will be equal to totalRecs.


If you want a consecutive range starting from a random point, simply subtract the size of the range from the random range (so if you're database is of size 20, the random generator will only produce output between 0 and 10).

Am I missing something?

0

精彩评论

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