gpt4 book ai didi

java - Monty hall 模拟未按预期运行

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:13 24 4
gpt4 key购买 nike

    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一个非常相似,但似乎没有人真正帮助解决主要问题。

我该怎么做才能使赔率更真实?关于清理代码的建议也将不胜感激。

编辑:代码现在可以运行了,我现在只是想把它精简一下。

最佳答案

在你的方法withoutswitch你需要改变

if(guess==1)
nsCorrect++;

if (curtains[guess] == 1)
nsCorrect++;

withswitch 方法相同。每次运行 for 循环后,您需要将 curtains 重置为 0。否则之前的 1 将在那里,并且在几次运行后 curtains 将只包含 1。

private static void resetCurtains(int[] curtains) {
for (int i = 0; i < curtains.length; i++) {
curtains[i] = 0;
}
}

每次在 for 循环中运行后调用该方法。

此外,我建议使用 {},即使语句是 1-liner:

if (curtrains[guess] == 1) {
nsCorrect++;
}

关于java - Monty hall 模拟未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24443493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com