programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools 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

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.

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)

Sheriff
Posts: 21208
87
Or use java.util.Random's nextInt(int n) method.

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

 You're not going crazy. You're going sane in a crazy word. Find comfort in this tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS