Homework: Simulating coin tosses until consecutive heads using R

吃可爱长大的小学妹 提交于 2019-12-01 21:15: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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!