繁体   English   中英

R 采样字母(字母)时如何检查下一个字母是否比前一个字母更大?

[英]R when sampling letters (LETTERS) how do I check if the next letter is a greater letter value then the previous one?

我需要继续打印(绘制)字母,直到下一个字母与前一个字母顺序不同。

一个例子是 CDEA,因为 A 不在 E 之后,所以抽奖次数为 4。我正在尝试使用 while 循环来执行此操作。

draw <- function() {

   drawletters <-  sample(LETTERS)
   drawnum <- 0


   while (drawletters > drawletters) {
      firstdraw <- drawletters
      drawletters <- sample(LETTERS)
      drawnum <- drawnum + 1
    }

   print(drawletters)

}

我了解我的条件语句在我的循环中是如何错误的,但我不知道 go 的最佳方法。

这是一种潜在的解决方案:

# Create an empty (NULL) vector to store the results of each run
results <- c()

# Create the function
draw <- function(){
  # Start with draw_num = 0
  draw_num <- 0
  # Draw a letter
  firstdraw <- sample(LETTERS, 1)
  # Add 1 to draw_num
  draw_num <- draw_num + 1
  # Draw another letter
  nextdraw <- sample(LETTERS, 1)
  # Add another 1 to draw_num
  draw_num <- draw_num + 1
  # Print the letters (you can omit this if you don't need it)
  print(firstdraw)
  print(nextdraw)
  # Then use a while loop to print the letters and add 1 to draw_num
  # until the next letter comes before the previous
    while(nextdraw > firstdraw) {
      firstdraw <- nextdraw
      nextdraw <- sample(LETTERS, size = 1)
      draw_num <- draw_num + 1
      print(nextdraw)
    }
  # Then print draw_num
  print(draw_num)
  # And append draw_num to the results vector
  results <<- c(results, draw_num)
}

# Run the function a bunch of times (e.g. run "draw()" 10X)
draw()


# Then you can see the average number of letters drawn across all runs
mean(results)
#>[1] 2.7

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM