【问题标题】:Random Number Generator / Coin Flip / A-B Generator - Run Until X in a Row in R随机数生成器/硬币翻转/A-B 生成器 - 在 R 中连续运行直到 X
【发布时间】:2015-10-16 21:08:33
【问题描述】:

我正在尝试生成随机结果,例如掷硬币。我想运行这个 A/B 或正面/反面生成器,直到我连续得到 x 个相同的结果。

我在网上找到了这个用于掷硬币的代码:

sample.space <- c(0,1)
theta <- 0.5 # this is a fair coin
N <- 20 # we want to flip a coin 20 times
flips <- sample(sample.space, 
size=N,
replace=TRUE,
prob=c(theta,1-theta))

这可以生成 20 次翻转,但我想做的是让“翻转模拟器”运行,直到我连续获得 x 个相同的结果。

【问题讨论】:

    标签: r coin-flipping


    【解决方案1】:

    你可以使用一个简单的循环

    n <- 10                                           # get this many 1s in a row
    count <- runs <- 0                                # keep track of current run, and how many total
    while(runs < n) {                                 # while current run is less than desired
        count <- count+1                              # increment count
        runs <- ifelse(sample(0:1, 1), runs+1, 0)     # do a flip, if 0 then reset runs, else increment runs
    }
    

    【讨论】:

      【解决方案2】:

      一种方法可能是生成大量的硬币翻转,并使用rle 函数识别您第一次获得指定的连续翻转次数:

      first.consec <- function(num.consec, num.flip) {
        flips <- sample(0:1, size=num.flip, replace=TRUE, prob=c(0.5, 0.5))
        r <- rle(flips)
        pos <- head(which(r$lengths >= num.consec), 1)
        if (length(pos) == 0) NA  # Did not get any runs of specified length
        else sum(head(r$lengths, pos-1))
      }
      set.seed(144)
      first.consec(10, 1e5)
      # [1] 1209
      first.consec(10, 1e5)
      # [1] 2293
      first.consec(10, 1e5)
      # [1] 466
      

      【讨论】:

        【解决方案3】:

        比@nongkrong 的回答长一点,但你实际上得到了一些输出:

        n <- 5
        out <- 2
        tmp2 <- 2
        count <- 0
        while (count < n-1) {
            tmp <- sample(0:1,1)
            out <- rbind(out, tmp)
            ifelse(tmp == tmp2, count <- count+1, count <- 0)
            tmp2 <- tmp
        }
        out <- data.frame(CoinFlip=out[-1])
        out
        

        例子:

        > out
          CoinFlip
        1        1
        2        0
        3        1
        4        0
        5        0
        6        0
        7        0
        8        0
        

        【讨论】:

          猜你喜欢
          • 2012-10-23
          • 1970-01-01
          • 1970-01-01
          • 2014-06-30
          • 2015-03-01
          • 1970-01-01
          • 2023-01-03
          • 1970-01-01
          • 2017-09-03
          相关资源
          最近更新 更多