Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Random number between size of an array  RSS feed

 
Steven Alvarez
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or use java.util.Random's nextInt(int n) method.
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and n is the size of the array
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!