Domanda

(Note: There are some similar problems, but I could not find an exact duplicate)

Question

Consider flipping a coin an arbitrary number of times. What is the probability that you obtain 2 heads before 3 tails?

Code

To simulate this, I set up 10000000 trials, where 0's are heads, 1's are tails, etc.

    ArrayList<Integer> listOfTosses=new ArrayList<Integer>();
    int numTrue=0;
    int numTrials=0;

    while(numTrials<10000000)
    {
       boolean record=false;
       boolean twoHeads=false;
       int counter=2;

         listOfTosses.add((int) Math.random()*2);
         listOfTosses.add((int) Math.random()*2);

        if(listOfTosses.get(0)==0 && listOfTosses.get(1)==0)
        {
            twoHeads=true;
            record=true;
        }

        listOfTosses.add((int) Math.random()*2);

       while(record=false)
       {

          if(listOfTosses.get(counter)==0 && listOfTosses.get(counter-1)==0)
          {
            twoHeads=true;
            record=true;
          }
          if(listOfTosses.get(counter)==1 
          && listOfTosses.get(counter-1)==1
          && listOfTosses.get(counter-2)==1)                   
         {
            twoHeads=false;
            record=true;
         }
           listOfTosses.add((int) Math.random()*2);
           counter++;
      }




       if(twoHeads==true)
       {
           numTrue++;
       }


       record=false;
       twoHeads=false;
       listOfTosses.clear();

       numTrials++;

    }
    System.out.print(numTrue/10000000.0);

Issue

The code compiles properly, but always gives me an answer of 1.0 (one can prove mathematically that the exact answer is 0.7).

È stato utile?

Soluzione

One typo: change while(record=false) to while(record==false).

On top of that, your while loop that runs while record == false isn't running. This is because listOfTosses.get(0) and listOfTosses.get(1) are both set to 0.

When you do listOfTosses.add((int) Math.random()*2);, it's actually equivalent to listOfTosses.add(((int) Math.random()) * 2);. Since Math.random() < 1, that gets turned into a 0. Do listOfTosses.add((int) (Math.random()*2)); instead.

Alternatively, instead of dealing with converting floats, consider the java.util.Random class. The nextInt(int n) function looks like what you need.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top