About two months have passed since I started studying java anew. I wrote a program that can confirm the convergence of the probability of rolling dice as a summary of the underlying variables, arrays, methods and so on. Execute it on the terminal, enter any number of times, the result will be displayed as a graph, and the probability of each will be calculated. If you shake it about 20,000 times, it will be very close to 1/6.
Dice_Probability.java
import java.util.Scanner;
import java.util.Random;
public class Dice_Probability{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of times you want to roll the dice> ");
int times = scan.nextInt();
int[] result = generateDice(times);
System.out.println("Display the result");
for (int i=0; i<result.length; i++){
System.out.printf("%2d", result[i]);
if((i+1) % 10 ==0){
System.out.println("");
}
}
System.out.println("The graph is as follows.");
drawGraph(result);
System.out.println("The probability of each eye appearing is");
double[] percentage = calcProbability(result);
for (int i=0; i<percentage.length; i++){
System.out.println((i+1) + "Eyes: " + percentage[i]);
}
}
public static int[] generateDice(int n){
Random rand = new Random();
int[] arr = new int[n];
for (int i=0; i<arr.length; i++){
arr[i] = rand.nextInt(6) + 1;
}
return arr;
}
public static void drawGraph(int[] arr){//Graph display method
int[] dottimes = {0,0,0,0,0,0};//Record the number of times the eyes appear
for (int i=0; i<arr.length; i++){
switch (arr[i]){
case 1:
dottimes[0]++;
break;
case 2:
dottimes[1]++;
break;
case 3:
dottimes[2]++;
break;
case 4:
dottimes[3]++;
break;
case 5:
dottimes[4]++;
break;
case 6:
dottimes[5]++;
break;
}
}
for (int i=0; i<=5; i++){
System.out.print((i+1) + " : ");//Display of rolls
for(int j=0; j<dottimes[i]; j++){//1~dice[i]Times*Show
System.out.print("*");
}
System.out.println("");//new line
}
}
public static double[] calcProbability(int[] arr){//Method for calculating probability. Receives eye data and returns the probability of each eye
int[] dottimes = {0,0,0,0,0,0};
for (int i=0; i<arr.length; i++){
switch (arr[i]){
case 1:
dottimes[0]++;
break;
case 2:
dottimes[1]++;
break;
case 3:
dottimes[2]++;
break;
case 4:
dottimes[3]++;
break;
case 5:
dottimes[4]++;
break;
case 6:
dottimes[5]++;
break;
}
}
double[] probability = {0,0,0,0,0,0};
for (int i=0; i<dottimes.length; i++){
probability[i] = (double)dottimes[i]/arr.length;
}
return probability;
}
}
Recommended Posts