Home > Blockchain >  Computing an R function with while loop
Computing an R function with while loop

Time:11-05

The shelves have initially n-1 animal books and 1 plant book, a book (either animal or plant) magically disappears from the shelves and is automatically replaced by another one. The while loop has to run while the shelves still contain at least one animal book and one plant book. The function has to return the time it took the process to stop and the type of book that took over the shelves

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

# n = number of books 

sim_books <- function (n) {
  n =50
  shelves <- c(rep(0, n - 1), 1)
  plant_books <- n-1
  animal_books <- 1
  
  while (shelves != 0){
    # time it took for the process to stop
    time_stop <- 
      #  type that took over the shelves
    final_books <- (plant_books|animal_books )
    
  }
  
  
  
  return(time_stop, final_books)
  
}

CodePudding user response:

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

CodePudding user response:

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