Android Question best method to generate random integer value

Markos

Active Member
Licensed User
Longtime User
Hi All

What is the best method using the rnd function or otherwise to create random integer values in the range of 0 to 255
 

Computersmith64

Well-Known Member
Licensed User
Longtime User
The problem with using Rnd to generate random numbers is that it uses the system clock to seed - so if you're generating a lot of numbers in quick succession, you will likely get the same number generated 2 or more times in a row. I ran into this issue with my Yahtzee game & worked around it by using Rnd to generate 8 random numbers for each die. Those 8 random numbers are loaded into an array & then I use Rnd to select one of the elements of the array. This generally minimizes sequential duplicates & tests I've done on 1,000,000+ rolls show that the spread of numbers is pretty even.

- Colin.
 
Upvote 0

Roycefer

Well-Known Member
Licensed User
Longtime User
You can also seed Rnd using System.nanoTime (via Reflection or JavaObject) or use System.nanoTime in place of DateTime.Now in my second snippet to ensure that consecutive calls give different values. You'd need an extremely fast computer to get consecutive calls to occur within the same nanosecond.
 
Upvote 0

JTmartins

Active Member
Licensed User
Longtime User
I use a combination of things for a card shuffle game...light sensor values,date & time, wifi signal strenght and network names are pretty helpfull for random seeds if you play around with them.
 
Upvote 0
Top