Homework: Simulating coin tosses until consecutive heads using R

前端 未结 1 570
感动是毒
感动是毒 2021-01-20 06:49

I am new to R hence asking here (haven\'t been able to find very helpful tutorials for simulation that are detailed.)

The problem statement is this

  1. S
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 07:25

    As this is homework, I would like to give you some pointers for #2 and #3.

    For #2, make a loop which keeps doing coin tosses and count the number of heads in a row. At every toss increase the count of tosses by 1 and when reaching the number of heads requested, just return the count of tosses.

    To get you started, this will do nbTosses tossesL

    coin <- c('h','t')
    
    ComputeNbTosses <- function(targetTosses) {
      nbtosses = 0;
      while (nbtosses < targetTosses) {
        nbtosses = nbtosses + 1
      }
      return(nbtosses);
    } 
    

    You just need to amend it to take in parameter targetHeads and exit the while loop only when you have reached the tagetHeads.

    For #3, put #2 in a function and then use set.seed(integer), to set the seed. Random numbers on a computer are not really random. Most of random generators allow you to set a seed. If you use the same seed you will get twice the same sequence of pseudo random numbers, this allows for debugging.

    EDIT: I changed #2 from a recursion to a normal loop, it will be easier to code for him.

    EDIT (Tip): This will count how many heads in a row you have, now you have to make the loop stop when you reach the target value of heads:

    coin <- c('h','t')
    
    ComputeNbTosses <- function(targetTosses) {
      nbTosses = 0;
      nbHeadsInRow = 0;
      allTosses = c();
      while (nbTosses < targetTosses) {
        toss = sample(coin,1,T)
        allTosses = c(allTosses, toss);
        if (toss == 'h') {
          nbHeadsInRow = nbHeadsInRow + 1;
        } else {
           nbHeadsInRow = 0;
        }
        nbTosses = nbTosses + 1
      }
      ret = list();
      ret$nbTosses = nbTosses;
      ret$nbHeadsInRowAtEnd = nbHeadsInRow;
      ret$allTosses = allTosses;
      return(ret);
    } 
    
    ComputeNbTosses(5);
    ComputeNbTosses(8);
    

    This will print how many heads in row you had when it reached nbTosses. This is not what you want. What you want is:

    • change the argument from targetTosses to targetHeadsInRow
    • change the condition in the while so that it stops when nbHeadsInRow reaches targetHeadsInRow.
    • what you need to return is nbTosses (the number of tosses to reach your condition)

    Let me know if anything is not clear.

    0 讨论(0)
提交回复
热议问题