title: Homework: Simulating coin tosses until consecutive heads using R
body: <p>I am new to R hence asking here (haven't been able to find very helpful tutorials for simulation that are detailed.) </p>
  
  <p>The problem statement is this </p>
  
  <ol>
  <li>Simulate a coin toss for 20 times and record the number of heads
  &amp; longest run of heads. </li>
  <li>Simulate a coin toss and record the number of flips necessary until 2,3,4 heads occur in sequence (consecutively) (negative binomial?)</li>
  <li>Make 100 runs with different seeds to find the distribution of items recorded.</li>
  </ol>
  
  <p>How does one go about solving this in the programming language R ? </p>
  
  <p>For 1, I did the following:</p>
  
  <pre><code>n=20                #no of trials
  y=NULL              #initializing a vector of NULL values   
  for (i in 1:n) {
      x=runif(1)      #random uniform
      if (x&lt;0.5) {    #if condition for assigning heads / tails
          y[i]='H'
      } else {
         y[i]='T'
      }
  }
  y                   #print the vector storing the heads and tails.
  </code></pre>
  
  <p>For 2, I understand that this is a case of negative binomial because it says "until 2,3,4 heads occur in sequence" . But I am not sure how to proceed to write the code in R or come up with the logic.</p>
  
  <p>For 3, I am guessing have to calculate the number of heads got in 100 runs, run lengths of heads. But what does it imply to set <em>different seeds</em>? I am unsure of that.</p>
  
  <p><strong>note</strong> This is a homework problem, yes (I am not able to tag it so). I do not need the code, just some pointers/ corrections/clarifications/suggestions would help. </p>
  
  <p><strong>edit</strong> For simulating 2, I tried out the following code on MATLAB - </p>
  
  <pre><code>head_count = 0;
  flip_count = 0;
  
  while (head_count &lt; 3)                  #counting for 3 multiple heads
      flip = rand(1);
      flip_count = flip_count+1;
      if (flip &gt; 0.5)
          head_count = head_count + 1;
      else 
           head_count = 0;       #invalidate head counts if not successive.
      end
  end
  disp(flip_count)
  </code></pre>
  
  <p>Please let me know if this logic is correct. And I can recreate it using R.</p>