#1
  1. o0o.o0o
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2001
    Location
    m00n
    Posts
    194
    Rep Power
    102

    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.

    Brett
  2. #2
  3. o0o.o0o
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2001
    Location
    m00n
    Posts
    194
    Rep Power
    102
    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.

    Code:
    package diceGame
    import java.util.*;
    
    public class RollableDice extends SixSidedDice
    {
      // constructor
      public RollableDice()
      {
        super();
      }
    
      // command
      public void roll()
      {
        this.setVisibleSide(this.randGenerator.nextInt(6)+1);
      }
      
      // componant
      Random randGenerator = new Random(System.currentTimeMillis());
      
    }
  4. #3
  5. No Profile Picture
    aHVoPw==
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jan 2001
    Posts
    1,058
    Rep Power
    15
    Originally posted by estrabd
    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.
    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.
    Visit my new IIS Tutorial Series!
  6. #4
  7. No Profile Picture
    Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Location
    India
    Posts
    7
    Rep Power
    0
    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...

IMN logo majestic logo threadwatch logo seochat tools logo