recursion - Solution tracking and Optimal Solution recursive Knapsack R -


i relatively new using r, hope me recursive knapsack problem. think first part correct, unable find items selected in optimal solution.

2 computing value function f

f  <- function(i,k){   if (i==0 || k==0){     output <- 0   } else if (length( w[i]) && w[i] > k) {     output <- f(i-1,w)   } else {     output <- max(v[i]+ f(i-1, k-w[i]), f(i-1,k))   }''    return(output) } f(4,15) 

3 tracking solution given state (i, k)

keep <- function(i,k){   if (k < w[i]){   keep(i,k) <- 0 } else if (f(i-1,k) <= v[i]+f(i-1,k-w[i])) {   keep(i,k) <- 1 } else {   keep(i,k) <- 0   }   return(keep)   } 

4 find optimal solution

selection <- rep(0,4) remainingcap <- k (i in 1:4)   if (keep(i, remainingcap) <- 1){   output <- 1   remainingcap <- (k-w[i]) }  else {   output <- 0 }   print(selection) 


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -