You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中编写代码判断何时收集齐全部3种玩具?

解决R语言中判断首次集齐全部3种玩具的问题

基于你已有的随机排序玩具序列,这里提供两种方法来找到首次集齐三种玩具时的收集次数:

方法1:使用dplyr进行向量式处理(推荐)

利用累积计算跟踪已收集的玩具种类,无需循环,效率更高:

library(tibble)
library(dplyr)

# 你已有的代码
rep("mouse", 3000) -> mouse
rep("dolphin", 5000) -> dolphin
rep("train", 2000) -> train
c(mouse, dolphin, train) -> toy

tibble(toy) %>% 
  slice_sample(prop = 1, replace = FALSE) -> df

# 新增逻辑:计算首次集齐三种玩具的步数
df %>%
  mutate(
    # 累积记录已收集的玩具种类
    collected_toys = accumulate(toy, ~ union(.x, .y), .init = character(0))[-1],
    # 判断当前是否集齐三种
    all_collected = map_lgl(collected_toys, ~ length(.x) == 3)
  ) %>%
  # 找到第一个满足条件的行,其行号就是所需步数
  filter(all_collected) %>%
  slice(1) %>%
  pull(row_number()) -> first_complete_step

# 输出结果
cat("首次集齐全部3种玩具需要收集", first_complete_step, "次\n")

方法2:基础R循环实现

如果你偏好基础R语法,也可以用循环逐步检查:

# 你已有的代码
rep("mouse", 3000) -> mouse
rep("dolphin", 5000) -> dolphin
rep("train", 2000) -> train
c(mouse, dolphin, train) -> toy
set.seed(123) # 可选:设置随机种子保证结果可复现
shuffled_toy <- sample(toy) # 直接用sample随机排序,比slice_sample更简洁

# 循环检查
collected <- character(0)
step <- 0

while(length(collected) < 3) {
  step <- step + 1
  current_toy <- shuffled_toy[step]
  collected <- union(collected, current_toy)
}

cat("首次集齐全部3种玩具需要收集", step, "次\n")

补充说明:

  • 两种方法核心逻辑一致:逐步跟踪已收集的玩具种类,直到包含全部3种时停止,记录此时的步数。
  • 如果需要多次模拟(比如计算平均步数),可以把上述逻辑封装成函数,用replicate()重复运行。

内容的提问来源于stack exchange,提问作者luciano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 09:56:03