Example
|
Example
|
Example
|
Example
|
To simulate rolling a die you could say: int die = (int)random(6) + 1;
This works because random(6) will give a random value in this range: 0 ≤ random(6) < 6. By casting to an int you will then have a value in the set {0, 1, 2, 3, 4, 5}. Then adding 1 to that gives a number in the set {1, 2, 3, 4, 5, 6}.
The second version of the method takes 2 arguments. The first argument is the lowest possible float value you would like to be able to get. The random number will be less than the second argument. To generate a random x coordinate between 100 and 200 (could be 100 but will always be less than 200) you could do : float x = random(100, 200);
ExampleTo give the int variable number a random value uniformly distributed over the set {9, 12, 15, 18, 21, 24, 27} do the following:number = (int)random(7) * 3 + 9; random(7) gives a float greater than or equal to 0 and less than 7. We choose 7 because there are 7 numbers in that set. When you cast that result to an int you get an int in the set {0, 1, 2, 3, 4, 5, 6}. When you multiply that by 3 you get a number in the set {0, 3, 6, 9, 12, 15, 18} and then finally when you add 9 you get the required set. |
|