views:

56

answers:

1

Basically I have to use a random function that can return a number between 0 and 2^16-1.

I am trying to make use of this and generate let's say, 6 intervals between 1 and 6 (thinking of dice poker). Basically use that one number that is randomly generated for me (I can specify range only) and preferably only have to call it once. Then take that number and "split" it into 6 dices where the values will be between 1-6.

I am a bit unsure of the technique one would use, one thing that comes to mind is bit masking but I am unsure if this is the right context.

From a binary point of view then it's reasonable to have the dice values between 0-5. That would give us the binary number 000-101. Now a max value of the random function return would be 101101101101101101 (six dices, each being "6") and in decimal it means the upper bound on the random int return would be 187245. The lower bound would be 0. Now let's say the random function returns us the number 66508, making it into binary form we get 010|000|001|111|001|100 and that's not good enough! In this case one of the dices would be 111 = 7 and we can't get that when the interval is supposed to be 0-5 (1-6) :(

I need to figure out a way a decimal within the limit range can contain six dices with the values 1-6 (0-5) but I am in some need of assistance.

+2  A: 

You can use the values x % 6, (x / 6) % 6, (x / 6^2) % 6, ... , (x / 6^5) % 6 where x is a number from your random number generator. There will be a bias if you do this though. You should reject x and reselect if it is greater than 6**6-1 if you want to avoid this bias.

Mark Byers
Lovely! I was sure mod was gonna be used in the solution. :)
Vlad
For a nice algorithm of how to generate uniform random numbers between 0 and n using a modulus you can see `java.util.Random.nextInt(int)`: http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int)
Joey