• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Random number between size of an array

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Or use java.util.Random's nextInt(int n) method.
 
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
and n is the size of the array
 
It's weird that we cook bacon and bake cookies. Eat this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic