r - 如何在 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)
解决方案
我们可以根据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
推荐阅读
- grails - 使用 grails 3.3 在命令对象中使用共享约束
- google-cloud-dataflow - 从数据流管道将任务排入 Google TaskQueue / Cloud Tasks 队列
- javascript - 使用 JS 为 facebook 调度程序获取正确的 unix 时间戳
- reactjs - 如何在字符串中应用 URL?
- ruby-on-rails - Rails turbolinks 多次提交远程真实表单
- sass - 为什么我的字体无法正确加载?
- excel - 将变量定义的范围内的每个元素相乘
- jwplayer - 尝试从 jwplayer 运行视频时突然出现错误 100013
- python - 与可互换字符匹配的字符串
- react-native - react-native-elements 叠加边框透明度