使用 while 循环计算 R 函数

Computing an R function with while loop

-> 我不知道如何计算进程停止所花费的时间,我觉得我犯了一些错误,功能似乎有点不对劲...

# y = number of books 

sim_books <- function (y) {
  y = 0
  shelves <- c(rep(0, y - 3), 1)
  plant_books <- y-3
  animal_books <- 1
  
  while (shelves != 0){
    # time it took for the function to stop running
    time_stop <- 
      
    
    
  }
  
  
  
  return(time_stop)
  
}

你可以试试这个方法。如果您有任何问题,请告诉我。

sim_books <- function (n) {
  x <- c(-1, rep(1, n-1))
  count <- 0
  while(!(sum(x) %in% c(n, -n))) {
    i <- sample(1:n, 1)
    x[i] <- x[i] * -1
    count <- count + 1
  }
  
  return(count)
}
sim_books(4)
[1] 7

您可以试试下面的代码

f <- function(n) {
  shelves <- c(rep(0, n - 1), 1)
  iter <- 0
  res <- list(shelves)
  while (var(shelves) != 0) {
    shelves <- (shelves + replace(rep(0, n), sample(n, 1), 1)) %% 2
    iter <- iter + 1
    res[[iter + 1]] <- shelves
  }
  list(trajectory = res, niter = iter)
}

你会看到

> f(7)
$trajectory
$trajectory[[1]]
[1] 0 0 0 0 0 0 1

$trajectory[[2]]
[1] 1 0 0 0 0 0 1

$trajectory[[3]]
[1] 1 0 0 1 0 0 1

$trajectory[[4]]
[1] 1 0 0 1 0 0 0

$trajectory[[5]]
[1] 0 0 0 1 0 0 0

$trajectory[[6]]
[1] 0 1 0 1 0 0 0

$trajectory[[7]]
[1] 0 1 0 1 1 0 0

$trajectory[[8]]
[1] 0 1 0 1 1 0 1

$trajectory[[9]]
[1] 0 1 1 1 1 0 1

$trajectory[[10]]
[1] 0 1 1 1 1 1 1

$trajectory[[11]]
[1] 0 0 1 1 1 1 1

$trajectory[[12]]
[1] 0 0 0 1 1 1 1

$trajectory[[13]]
[1] 0 0 1 1 1 1 1

$trajectory[[14]]
[1] 1 0 1 1 1 1 1

$trajectory[[15]]
[1] 1 0 1 1 0 1 1

$trajectory[[16]]
[1] 1 0 1 1 1 1 1

$trajectory[[17]]
[1] 1 1 1 1 1 1 1


$niter
[1] 16