Skip to content

Instantly share code, notes, and snippets.

@OsandaMalith
Last active January 1, 2018 13:05
Show Gist options
  • Save OsandaMalith/484902fc8a25c7972495 to your computer and use it in GitHub Desktop.
Save OsandaMalith/484902fc8a25c7972495 to your computer and use it in GitHub Desktop.
import java.util.Random;
public class dice {
// Codded by Osanda Malith Jayathissa (@OsandaMalith)
/*
Write a program that simulates the rolling of two dice. The program should use rand to roll the first die and should use rand again to roll the second die. The sum of two values should then be calculated. [Note : Each die can show an integer value from 1 to 6, so the sum of the two values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums.] Note that there are 36 possible combinations of the two dice. Your program should roll the two dice 3,600 times. Use a one_dimensional array to tally the numbers of times each possible sum appears. Print the results in a tabular format. Also, determine if the totals are reasonable (i.e., there are six ways to roll a 7, so approximately one-sixth of all the rolls should be 7).
http://www.freemathhelp.com/rolling-dice.html
Outcome List of Combinations Total
2 1+1 1
3 1+2, 2+1 2
4 1+3, 2+2, 3+1 3
5 1+4, 2+3, 3+2, 4+1 4
6 1+5, 2+4, 3+3, 4+2, 5+1 5
7 1+6, 2+5, 3+4, 4+3, 5+2, 6+1 6
8 2+6, 3+5, 4+4, 5+3, 6+2 5
9 3+6, 4+5, 5+4, 6+3 4
10 4+6, 5+5, 6+4 3
11 5+6, 6+5 2
12 6+6 1
Outcome Probability
2 1/36 = 2.78%
3 2/36 = 5.56%
4 3/36 = 8.33%
5 4/36 = 11.11%
6 5/36 = 13.89%
7 6/36 = 16.67%
8 5/36 = 13.89%
9 4/36 = 11.11%
10 3/36 = 8.33%
11 2/36 = 5.56%
12 1/36 = 2.78%
*/
public static void main(String[] args) {
int sum, dice1, dice2, actual = 0;
int[] Total = new int[13];
int[] ways = { 0, 0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1 };
for (int i = 0; i < 36000; i++) {
sum = 0;
dice1 = new Random().nextInt(6) + 1;
dice2 = new Random().nextInt(6) + 1;
sum = dice1 + dice2;
Total[sum]++;
}
for (int i = 0; i < 13; i++) actual += Total[i];
System.out.printf("%-4s %s %-11s %s%n", "Sum", "Total", "Expected",
"Actual");
for (int i = 2; i < 13; i++)
System.out.printf("%-4d %-5d %-10.5f %2.5f%n", i, Total[i],
100.0 * ways[i] / 36, 100 * (double) Total[i] / actual);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment