Monty Hall 問題
先日TVでみて気になっていた。
10万回試行して、本当に確率がその通りになるのかどうか。
まだ作法がよくわからず、「初期化されていない」だのと怒られるので
int opend = 9; など、気に入らない部分も多いが、一応はじめての作品。
実行結果:
C:\Users\lohin\Desktop\javasample>java Run
1000000 times.
Success rate with Change:66.6516
Success rate with No Change:33.329002
ソースはこんな感じ:
import java.util.Random;
import java.util.ArrayList;
class Run {
public static void main(String[] args) {
int times = 1000000;
System.out.println(times + " times.");
MontyHall Change = new MontyHall(true, times);
Change.doGames();
System.out.println("Success rate with Change:" + Change.getRate());
MontyHall NoChange = new MontyHall(false, times);
NoChange.doGames();
System.out.println("Success rate with No Change:" + NoChange.getRate());
}
}
class MontyHall {
boolean isChange;
int times;
int bingo;
float rate;
Random r;
MontyHall(boolean isChange, int times) {
this.isChange = isChange;
this.times = times;
this.bingo = 0;
this.rate = 0;
this.r = new Random();
}
public void doGames() {
if (this.isChange) {
for (int i = 0; i < this.times; i++) {
gameWithChange();
}
} else {
for (int i = 0; i < this.times; i++) {
gameWithNoChange();
}
}
}
public void gameWithChange() {
int doors[] = {0, 1, 2};
int correct = r.nextInt(3);
int choice = r.nextInt(3);
// open a door which player does not chose
int opend = 9;
if (correct == choice) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
for (int i = 0; i < doors.length; i++) {
if (i != correct) {
tmp.add(i);
}
}
opend = tmp.get(r.nextInt(2));
} else {
for (int i = 0; i < doors.length; i++) {
if (i == correct) continue;
if (i == choice) continue;
opend = i;
}
}
int left = 9;
for (int i = 0; i < doors.length; i++) {
if (i == choice) continue;
if (i == opend) continue;
left = i;
}
if (left == correct) {
this.bingo++;
}
}
public void gameWithNoChange() {
int correct = r.nextInt(3);
int choice = r.nextInt(3);
if (choice == correct) {
this.bingo++;
}
}
public float getRate() {
return ((float)this.bingo / (float)this.times) * 100;
}
}