尝试多次复制结果

问题描述 投票:0回答:1

我这里有一个模拟游戏,作为一个有趣的项目,它有一个加载的硬币翻转,第一个分别获得 15 个正面或反面的人获胜。我正在尝试复制它,以便游戏玩 x 次,并存储得分结果和获胜结果。这是我编写的代码,其功能是一次性运行,但我似乎无法使其可重播,任何帮助表示赞赏:

MeScore256<-0
OppScore256<-0
turns<-0
Fence <- c("Me", "Opps")  #Names

while(MeScore256<15 & OppScore256<15){
  flip<-sample(c(0,1), size = 1, replace = TRUE, prob = c(0.4,0.6))
  if (flip==1){
    MeScore256<-MeScore256+1
  }else{
    OppScore256<-OppScore256+1
  }
  turns<-turns+1
  }
print(MeScore256)
print(OppScore256)

if (MeScore256==15){print ("you win round 256")
   
} 

if (OppScore256==15){print("Opps win 256 :(")}
  

尝试使用“复制”功能,总是失败,我认为这与分数计数器的工作方式和上一轮的分数有关,但我不是100%确定。

r simulation replication coin-flipping
1个回答
0
投票

您可以让函数将迭代的结果存储在 tibble 中,然后使用

map
运行 10 次迭代,然后使用
bind_rows()
获取一组结果:

library(tidyverse)

MeScore256 <- 0
OppScore256 <- 0
turns <- 0
Fence <- c("Me", "Opps") # Names

# Function
run_sim <- \(MeScore256 = 0, OppScore256 = 0, turns = 0){
  while (MeScore256 < 15 & OppScore256 < 15) {
    flip <- sample(c(0, 1), size = 1, replace = TRUE, prob = c(0.4, 0.6))
    if (flip == 1) {
      MeScore256 <- MeScore256 + 1
    } else {
      OppScore256 <- OppScore256 + 1
    }
    turns <- turns + 1
  }
  # print(MeScore256)
  # print(OppScore256)

  if (MeScore256 == 15) {
    # print("you win round 256")
    who_wins <- "you win round 256"
  }

  if (OppScore256 == 15) {
    # print("Opps win 256 :(")
    who_wins <- "Opps win 256 :("
  }
  
  tibble(MeScore256 = MeScore256, OppScore256 = OppScore256, who_wins = who_wins)
}

# Run 10 times and store results
set.seed(2)
map(1:10, run_sim) |> 
  bind_rows()

#> # A tibble: 10 × 3
#>    MeScore256 OppScore256 who_wins         
#>         <dbl>       <dbl> <chr>            
#>  1         15           8 you win round 256
#>  2         15           8 you win round 256
#>  3         10          15 Opps win 256 :(  
#>  4         15           1 you win round 256
#>  5         15           6 you win round 256
#>  6         15           0 you win round 256
#>  7         15           4 you win round 256
#>  8         15           7 you win round 256
#>  9         15           5 you win round 256
#> 10         15           1 you win round 256

创建于 2024-04-03,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.