Today's program is a simple dice roll program that tests the proficiency of java.util.random. I got the idea from /r/dailyprogrammer.
1: /*
2: Name: Kevin Achenbach
3: Date: 7/12/2014
4: Project: test a RNG to see how random it actually is. Use 6 sided dice as the test
5: */
6: package dice;
7: import java.util.Random;
8: public class Dice {
9: static int diceRolls[] = {10,100,1000,10000,100000,1000000};
10: public static void main(String[] args) {
11: System.out.print("# of Rolls 1s 2s 3s 4s 5s 6s\n");
12: System.out.print("====================================================\n");
13: for(int i = 0; i< diceRolls.length; i++) {
14: System.out.format("%-11d", diceRolls[i]);
15: float percent[] = rollDice(6,diceRolls[i]);
16: //Display results
17: for(int j = 1; j<percent.length;j++) {
18: percent[j] = percent[j]*100;
19: String str = String.format("%2.02f", percent[j]);
20: System.out.print(str + "% ");
21: }
22: System.out.print("\n");
23: }
24: }
25: static float[] rollDice(int arraySize ,int numberOfRolls) {
26: //can assume the all array values are zero at initialization
27: int testData[] = new int[arraySize+1];
28: Random rand = new Random();
29: int x;
30: float percent[] = new float[arraySize+1];
31: for(int i = 0; i<numberOfRolls; i++) {
32: x = rand.nextInt(6)+1;
33: testData[x]++;
34: }
35: for(int j = 0; j<arraySize+1;j++) {
36: percent[j] = ((float)testData[j])/numberOfRolls;
37: }
38: return percent;
39: }
40: }
Results:
The results were as expected. Java.util.Random did not favor any number in particular as the number of rolls increased. A few things I learned while doing this:
- line 36: converting two ints to a float by dividing is a bit tricky. The conversion to a float happens after the division occurs. This means that two integers dividing into a percentage will always come out as 0.0 unless the percentage is 100%. To avoid this cast the numerator as a float before dividing.
- Java.util.Random is INCREDIBLY quick. I ran the nextInt method over a million times yet the total run time was still under a second.
No comments:
Post a Comment