Steven Alvarez

Ranch Hand

Posts: 66

posted 10 years ago

Math.random() generates a random double between 0.0 and 1.0 (including 0.0, but

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

*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)

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." *~Joe Strummer*

sscce.org

posted 10 years ago

Or use java.util.Random's nextInt(int n) method.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions

posted 10 years ago

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.

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.

Enjoy, Chander

SCJP 5, Oracle Certified PL/SQL Developer