- topic
写一个验证掷骰子概率的程序,同时投掷 2 颗 6 面骰子 n 次,计算其和得到 各数字的概率
-
Analysis
According to my own analysis steps, first analyze and calculate the sum of the numbers obtained by 2 6-sided dice. But how to calculate the sum? That is to generate a number between Random and 1-6 (new Random ().nextInt(6)+1) each time through a random number. This represents a dice. Each time you write the number that appears twice, it adds up to 2 to get the number.的和。 The sum. Then use the sum as the key of the Map, and then the Value is the number of times. The first is 1 later you can use the new Java8 Map method merge. I haven't used it here for the time being because it is easy to understand. The outside is n cycles. At this time, there are already n times of different values in the map. The next step is to calculate the probability. After analysis, the denominator is n and the number of occurrences is the numerator. This player who often plays mahjong should know that both are 1 and 2 and both are 6 and 12. So no matter how many times they appear and the range is 2-12. So according to this cycle, the probability of each occurrence is calculated. -
Code
package com.dairuijie.demo.study;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
/**
*
* @模块名:Day01
* @包名:com.dairuijie.demo.study
* @描述:SievesTest.java @版本:1.0
* @创建人:drj
* @创建时间:2020年3月28日下午12:35:14
*/
public class SievesTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
try {
System.out.print("请输入次数:");
Integer read = Integer.valueOf(scan.nextLine());
if (read == 0) {
break;
}
System.out.println("输入数据:" + read);
long s = System.currentTimeMillis();
Random r = new Random();
BigDecimal total = new BigDecimal(read);
Integer temp = 0;
Map<Integer, Object> hashMap = new HashMap<>();
for (int i = 0; i < read; i++) {
// 6次
for (int j = 0; j < 2; j++) {
// 2 颗
int key = r.nextInt(6) + 1;
temp = +key;
if (hashMap.containsKey(key) && j == 1) {
hashMap.put(temp, Integer.valueOf(hashMap.get(temp).toString()) + 1);
temp = 0;
} else if (j == 1) {
hashMap.put(temp, 1);
}
}
}
if (hashMap != null && hashMap.size() > 0) {
for (int i = 2; i < 13; i++) {
if (hashMap.get(i) != null) {
System.err.println(String.format("数字为%s的概率=%s", i,
(new BigDecimal(Integer.valueOf(hashMap.get(i).toString()))
.divide(total, 2, BigDecimal.ROUND_HALF_UP).setScale(2))
.multiply(new BigDecimal(100))
+ "%"));
}
}
}
long e = System.currentTimeMillis();
System.out.println("耗时:" + (e - s) + "ms");
} catch (Exception e) {
// TODO Auto-generated catch block
System.err.println("格式有误!");
}
}
scan.close();
}
}
- Result analysis The
larger the last number of times, the probability of each occurrence is basically the same.