Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Random Number Genration

Divya Venkatesh
Greenhorn

Joined: Nov 05, 2002
Posts: 28
Hi,
I need help in generating Random numbers between 2 integers say 1 and 20.
Also How do i ensure that it produces different values everytime i run the program.

Divya
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
By defination, random number generator generate a number between 0 and 1 randomly, so you use
19 * random + 1
to genrator a random number between 1 and 20.
Ranch Hand

Joined: Jan 10, 2003
Posts: 284
a series of random numbers between 1 and 20 ... do they have to be different just within the set of generated numbers? or a different set of numbers to any previously generated? or does every number have to be different every time?

giddee up
Ranch Hand

Joined: Jan 10, 2003
Posts: 284
maybe you could compare each number with the previously generated numbers using an if-else statement, and throw the number away if it is not different, but if it is, add it to the array?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18670
By defination, random number generator generate a number between 0 and 1 randomly, so you use
19 * random + 1
to generator a random number between 1 and 20.

Assuming you want integer values from 1 to 20 - try multiplying by 20 rather than 19. A general method is:

Math.random() uses the system time as a seed, so if you run it more than once it will not repeat the same sequence each time. You certainly may see some of the same values appear again of course. If that's not what you want, you'll need to explain more clearly.

"I'm not back." - Bill Harding, Twister
Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
private static int throwDice(){
return 1+(int)(Math.random()*6);
//Math.random returns a double value between 0.0 and 6.0 and cast it
//to int and adds one. So the return value of thrwoDice() is an int
//number between 1 and 7.
Is the result of "throwDice()" an int between 1 and 6 or 1 and 7?
Thomas
Ranch Hand

Joined: Jan 10, 2003
Posts: 284
my guess is -
if the code didnt have a 1+ in front of the random number that is cast to int, the result would be between 0 and 6, but with the plus, it must be between 1 and 7?
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
The answer to Thomas' question is an int between 1 and 6. Thomas, please don't post the same question in multiple forums.

I agree. Here's the link: http://aspose.com/file-tools

subject: Random Number Genration