用于計算概率,無需通過復(fù)雜的數(shù)學(xué)公式進(jìn)行具體場景的概率計算,只需用隨機數(shù)模擬出相關(guān)場景,即可得到對應(yīng)概率。
計算生日重復(fù)的概率
計算30個人的班級,生日出現(xiàn)重復(fù)的概率。
代碼如下:
public class 隨機算法1_計算重復(fù)生日的概率 {
public static void main(String[] args) {
int N = 1000 * 10;
int n = 0;
//0-365隨機產(chǎn)生數(shù)字,有沒有碰撞
for (int i = 0; i < N; i++) {
int[] x = new int[365];
for (int j = 0; j < 30; j++) {
int y = (int) (Math.random() * 365);
if (x[y] == 1) {
n++;
break;
} else {
x[y] = 1;
}
}
}
double rate = (double) n / N;
System.out.println(rate);
}
}
24點
給四張撲克牌,點數(shù) 1 ~ 10
用 + - * / 運算,使得最后結(jié)果為 24
代碼如下:
import java.util.Scanner;
import java.util.Stack;
public class 隨機算法2_24點 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String[] ss = sc.nextLine().split(" ");
f(ss);
}
private static void f(String[] ss) throws Exception {
for (int i = 0; i < (1000 * 100); i++) {
String[] buf = new String[7]; //4張牌,3個運算符;
for (int j = 0; j < 4; j++) {
buf[j] = ss[j]; //給4張牌賦值
}
for (int j = 4; j < 7; j++) {
buf[j] = createSymol();
}
shuffle(buf);
if (caculate(buf)) {
show(buf);
break;
}
}
}
private static String createSymol() {
int n = (int) (Math.random() * 4);
if (n == 0) {
return "+";
}
if (n == 1) {
return "-";
}
if (n == 2) {
return "*";
}
return "/";
}
//洗牌
private static void shuffle(String[] x) {
for (int i = 0; i < x.length; i++) {
int index = (int) (Math.random() * x.length);
String temp = x[i];
x[i] = x[index];
x[index] = temp;
}
}
//計算
private static boolean caculate(String[] data) throws Exception {
Stack s = new Stack();
try {
for (int i = 0; i < data.length; i++) {
if (data[i].equals("+") || data[i].equals("-") || data[i].equals("*") || data[i].equals("/")) {
int a = Integer.parseInt(s.pop().toString());
int b = Integer.parseInt(s.pop().toString());
s.push(caculate_detail(a, b, data[i]) + "");
} else {
s.push(data[i]);
}
}
} catch (Exception e) {
return false;
}
if (s.size() == 1 && s.pop().equals("24")) {
return true;
}
return false;
}
private static int caculate_detail(int a, int b, String operator) throws Exception {
if (operator.equals("+")) {
return a + b;
}
if (operator.equals("-")) {
return a - b;
}
if (operator.equals("*")) {
return a * b;
} else {
if (a % b != 0) {
throw new Exception("can not /");
} else {
return a / b;
}
}
}
//結(jié)果
private static void show(String[] data) {
Stack s = new Stack();
for (int i = 0; i < data.length; i++) {
if (data[i].equals("+") || data[i].equals("-") || data[i].equals("*") || data[i].equals("/")) {
s.push("(" + s.pop() + data[i] + s.pop() + ")");
} else {
s.push(data[i]);
}
}
System.out.println(s.pop());
}
}