March 13th, 2002, 10:52 AM
getting Random ints
I built a class to model a six-sided dice. I am trying to build a reliable "roll()" function that will set the visible side according using the Random class in java.util.*.
I can instantiate a Random object, and get the range I want by doing a Random.nextInt(7), however I have observed that when I run this in a loop I do not get the psuedo-random distribution I would expect. Instead I get consectutive results that contain 2,3,4 and sometimes 5 of the SAME number in a row.
Does anyone know how to rememdy this problem? Thanks.
March 14th, 2002, 11:34 AM
Ha! I am answering my own question...
The deal with java.util.Random is that it needs to be created as a class componant, and not inside a method. Otherwise, since it is psuedo random algorithm, you will get some not so random results if you recreate the object every time you call the method.
public class RollableDice extends SixSidedDice
public void roll()
Random randGenerator = new Random(System.currentTimeMillis());
March 16th, 2002, 01:19 AM
Hmm... thanks for reminding me! I almost forgot about that!
I have it in that situation for one of my scripts now Gotta fix that.
March 30th, 2002, 01:17 AM
u can try this ...
r.nextInt(1000) % 7;
i am sure..u will not have that repetition problems...
if u r still not satisfied with the result try changin the 1000 to 10000...