如何修改R语言硬币翻转游戏的While循环代码?
R语言硬币翻转游戏模拟代码修改
需求说明
玩家持续掷硬币,首次掷出反面立即被淘汰。现有代码已能生成模拟结果数据框,需补充以下规则:
- 若最后一轮有多名玩家被淘汰,新增一轮列,所有玩家标记为
eliminated - 若最后一轮仅有一名玩家被淘汰,新增一轮列,该玩家标记为
winner,其余玩家标记为eliminated
现有代码
num_players <- 3 results <- data.frame(player = paste0("player", 1:num_players)) status <- rep("playing", num_players) seen_tails <- rep(FALSE, num_players) round <- 1 # simulation while (any(seen_tails == FALSE)) { coin_flips <- ifelse(runif(num_players) > 0.5, "heads", "tails") seen_tails <- ifelse(coin_flips == "tails", TRUE, seen_tails) current_round <- ifelse(status == "playing", coin_flips, "eliminated") status <- ifelse(seen_tails == TRUE, "eliminated", status) results <- cbind(results, current_round) colnames(results)[ncol(results)] <- paste0("round_", round) round <- round + 1 } num_tails_last_round <- sum(results[,ncol(results)] == "tails")
当前运行结果示例
> results player round_1 round_2 round_3 1 player1 heads heads tails 2 player2 tails eliminated eliminated 3 player3 heads heads tails > num_tails_last_round [1] 2
期望输出
情况1:多名玩家最后一轮淘汰
> results player round_1 round_2 round_3 round_4 1 player1 heads heads tails eliminated 2 player2 tails eliminated eliminated eliminated 3 player3 heads heads tails eliminated
情况2:仅一名玩家最后一轮淘汰
> results player round_1 round_2 round_3 round_4 1 player1 heads heads tails winner 2 player2 tails eliminated eliminated eliminated 3 player3 heads tails tails eliminated
修改实现方案
在现有代码的最后,添加一段逻辑来生成并新增最终轮列:
num_players <- 3 results <- data.frame(player = paste0("player", 1:num_players)) status <- rep("playing", num_players) seen_tails <- rep(FALSE, num_players) round <- 1 # simulation while (any(seen_tails == FALSE)) { coin_flips <- ifelse(runif(num_players) > 0.5, "heads", "tails") seen_tails <- ifelse(coin_flips == "tails", TRUE, seen_tails) current_round <- ifelse(status == "playing", coin_flips, "eliminated") status <- ifelse(seen_tails == TRUE, "eliminated", status) results <- cbind(results, current_round) colnames(results)[ncol(results)] <- paste0("round_", round) round <- round + 1 } num_tails_last_round <- sum(results[,ncol(results)] == "tails") # 新增最终轮列逻辑 final_round_col <- rep("eliminated", num_players) if (num_tails_last_round == 1) { # 找到最后一轮掷出tails的玩家,标记为winner winner_idx <- which(results[,ncol(results)] == "tails") final_round_col[winner_idx] <- "winner" } # 绑定新列并设置列名 results <- cbind(results, final_round_col) colnames(results)[ncol(results)] <- paste0("round_", round)
关键修改点
- 计算最后一轮淘汰的玩家数量
num_tails_last_round后,初始化最终轮列为全eliminated - 当仅1人淘汰时,定位该玩家的索引,将对应位置改为
winner - 将最终轮列绑定到结果数据框,列名按现有规则命名为
round_加当前轮次值
内容的提问来源于stack exchange,提问作者konofoso
相关产品推荐
相关产品推荐

