import java.util.Scanner;
import static java.lang.System.*;
import static java.lang.Math.*;
import java.util.Random;
public class Montyhall
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of attempts:");
int attempts = keyboard.nextInt();/*Decide how many times you want this to
run. The larger the number, the more realistic an answer you will get.*/
int curtains[] = new int[3]; //like the game show, one of these will be a winner
Random rand = new Random(); /*sets the methods up with the same random seed, which
otherwise changes by the milisecond and could influence the response*/
withoutswitch(curtains, attempts, rand);
withswitch(curtains, attempts, rand);
}
public static void withoutswitch(int curtains[], int attempts, Random rand)
{
int nsCorrect=0;
for(int x=0; x < attempts; x++)
{
int winner = rand.nextInt(3);//Sets the winner to 1, leaving the other two at 0.
curtains[winner] = 1; //It then checks to see if they are the same,
int guess = rand.nextInt(3); //a 1/3 chance, roughly.
if(curtains[guess]==1){
nsCorrect++;
}
curtains[0]=0;
curtains[1]=0;
curtains[2]=0;
//the player never changes their decision, so it does not matter if a door is opened.
}
System.out.println("Number of successes with no switch: " + nsCorrect);
}
public static void withswitch(int curtains[], int attempts, Random rand)
{
int ysCorrect=0;
int goat = 0;
for(int x=0; x < attempts; x++)
{
int winner = rand.nextInt(3);
curtains[winner] = 1;
int guess = rand.nextInt(3);
goat = rand.nextInt(3);//one of the doors is opened
while(goat == winner || goat == guess)//the opened door is randomized until
goat = rand.nextInt(3); //it isn't the guess or the winner.
int guess2 = rand.nextInt(3);
while(guess2 == guess || guess2 == goat)
guess2 = rand.nextInt(3);//the second guess goes through a similar process
if(curtains[guess2]==1){
ysCorrect++;
}
curtains[0]=0;
curtains[1]=0;
curtains[2]=0;
}
System.out.println("Number of successes with a switch: " + ysCorrect);
}
}
對不起,這有點凌亂,我試圖回到編碼後幾乎一年的間隙。第一部分的功能如預期,大概有1/3的成功機會。然而,第二個應該給我一個2/3的機會,但是我仍然可以獲得與開關大致相同的數量,就像沒有開關一樣。我瀏覽了這個網站,大部分發現了我不熟悉的Java之外的東西。 This其中一個非常相似,但似乎沒有人真正幫助解決主要問題。蒙蒂大廳模擬沒有按預期運行
我該怎麼做才能讓賠率更加真實?清除代碼的建議也將受到讚賞。
編輯:代碼現在功能,我現在只是想減少它。
你可能會看到http://stackoverflow.com/questions/24208682/themontyhallparadox-is-this-right – pjs