首页 > 解决方案 > 如何在 r 中创建一个 bday 计数器以在 5 个相同的 bday 发生后退出 while 循环

问题描述

如何在同一天的 5 天完成后创建一个 while 循环以找到一个 bday 计数器以停止 while 循环。(数字 1 至 365)

n_people <- 0 # people counter, start at zero
bday_list <- rep(0, 365) # bday counter, each day starts with count = 0
bday_list
new_person <-sample(1:2, size = 1, replace = TRUE)
bday_list[new_person]
table[bday_list]
new_person
# no defined end to this problem/task!
while (n_people != 365) {
  # talk to my first person, increment counter
  n_people <- n_people + 1
  n_person <- sample(1:365, size = 1, replace = TRUE)

标签: r

解决方案


我们可以根据bday_list向量的位置更新向量,并在向量中的任何值达到 5 时停止。

bday_list <- rep(0, 365)
counter <- 0

while (all(bday_list < 5)) {
  n_person <- sample(1:365, size = 1)
  bday_list[n_person] <- bday_list[n_person] + 1
  counter <- counter + 1
}

cat('\nThe while loop exited after ', counter, ' iterations and the number is',
    which(bday_list == 5))

#The while loop exited after  332  iterations and the number is 119

推荐阅读