Pages

Wednesday, April 08, 2015

Write a program that Roll Dice 6000000 times

Input:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.Random;

public class RollDie {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Random rnd = new Random(); // random number generator

        int frequency1 = 0; // maintains count of 1s rolled
        int frequency2 = 0; // count of 2s rolled
        int frequency3 = 0; // count of 3s rolled
        int frequency4 = 0; // count of 4s rolled
        int frequency5 = 0; // count of 5s rolled
        int frequency6 = 0; // count of 6s rolled


        int face; // most recently rolled value
        
        // tally counts for 6,000,000 rolls of a die
        for (int roll = 1; roll <= 6000000; roll++) {
            face = 1 + rnd.nextInt(6);
            // determine roll value 1-6 and increment appropriate counter
            switch (face) {
                case 1:
                    ++frequency1; // increment the 1s counter
                    break;
                case 2:
                    ++frequency2; // increment the 2s counter
                    break;
                case 3:
                    ++frequency3; // increment the 3s counter
                    break;
                case 4:
                    ++frequency4; // increment the 4s counter
                    break;
                case 5:
                    ++frequency5; // increment the 5s counter
                    break;
                case 6:
                    ++frequency6; // increment the 6s counter
                    break; // optional at end of switch
            } // end switch
        } // end for

        System.out.println("Face\tFrequency"); // output headers
        System.out.printf("1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n",
                frequency1, frequency2, frequency3, frequency4,
                frequency5, frequency6);

    }
}

Output / Run:

Face Frequency
1 999981
2 1000458
3 1000487
4 999078
5 999474
6 1000522
BUILD SUCCESSFUL (total time: 1 second)

No comments:

Post a Comment