Computing an R function with while loop

Viewed 47

-> I couldn't figure out how to compute the time it took the process to stop and I feel like I made a few errors, the function seems a bit off...

# 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)
  
}

2 Answers

You may try this way. If you have any questions, please let me know.

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

You can try the code below

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)
}

and you will see

> 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
Related