Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Random number between size of an array

Steven Alvarez
Ranch Hand
Posts: 66
How would I generate a random number that is between the size of an array? For example lets say the array's length is 5, how would I then generate a number between 0 and 4? Or lets says the array length is 9, how would I generate a number between 0 and 8? Thanks for any help.

marc weber
Sheriff
Posts: 11343
Math.random() generates a random double between 0.0 and 1.0 (including 0.0, but not including 1.0). So multiplying this by your array's length would give you a random double between 0.0 and your length (including 0.0, but not including the length). Casting to type int will truncate the result (so that the maxium value will be length - 1).

(int)(Math.random() * myArray.length)

Rob Spoor
Sheriff
Posts: 21090
85
Or use java.util.Random's nextInt(int n) method.

chander shivdasani
Ranch Hand
Posts: 206
if you dont want to use any built in function then try this formula
Random no R(n) = (aR(n-1) + b)mod n where a = any initial value , b= any offset and R is the previous Random no ,keep R(n-1)=1 for the first case.It is also known as Linear congruential Generator .Check out Wikipedia for a detailed explanation.

chander shivdasani
Ranch Hand
Posts: 206
and n is the size of the array