Computer Science Canada

randomizing

Author:  rto [ Tue Nov 25, 2008 3:50 pm ]
Post subject:  randomizing

in turing all i would have to do is enter randint(variable, range) but instead java has to be difficult. anybody able to give me the method i would use? i want to be able to have 4 possible choices and java will randomly pick one. (ie. choice a will be referred to '1', choice b will be referred to '2' etc.)

any ideas?

Author:  Insectoid [ Tue Nov 25, 2008 4:09 pm ]
Post subject:  RE:randomizing

use Math.random (). This returns a random decimal between 0 and 1. So (int) (Math.random ()*4) will give a random number between 1 and 4 (I think...Haven't used it in a while). (int) will convert the random number to an integer. I don't think it rounds, I think it just cuts off the decimal..Though I may be wrong...

Author:  OneOffDriveByPoster [ Tue Nov 25, 2008 4:31 pm ]
Post subject:  Re: RE:randomizing

insectoid @ Tue Nov 25, 2008 4:09 pm wrote:
use Math.random (). This returns a random decimal between 0 and 1. So (int) (Math.random ()*4) will give a random number between 1 and 4 (I think...Haven't used it in a while). (int) will convert the random number to an integer. I don't think it rounds, I think it just cuts off the decimal..Though I may be wrong...
The range is [0, 1). So if you have choices in range [1, 4], you need to multiply by 4 to get range [0, 4). Cast to int to get [0, 3] and add one to get [1, 4].

Author:  Horus [ Tue Nov 25, 2008 10:47 pm ]
Post subject:  RE:randomizing

there's so many random function is java.

this is what I use:

import java.util.Random;


rdmNum=Random.nextInt(x);

the range is 0 to x-1

Author:  Sur_real [ Mon Dec 08, 2008 7:10 pm ]
Post subject:  Re: randomizing

There are so many you mean
(sorry, just can't help myself)

Author:  Tony [ Mon Dec 08, 2008 7:20 pm ]
Post subject:  Re: RE:randomizing

What, that's it?
Horus @ Tue Nov 25, 2008 10:47 pm wrote:
there's so many random function is java.

There are so many random functions in Java.

Wink

Author:  Sur_real [ Tue Dec 09, 2008 10:45 am ]
Post subject:  RE:randomizing

lol didn't notice that...

Author:  [Gandalf] [ Tue Dec 09, 2008 4:41 pm ]
Post subject:  RE:randomizing

Question's already been answered thoroughly, locked.


: