r - knapsack() vector length issues -


when run

weights <- 1:50 profits <- 1:50 library(adagio) knapsack(w = weights, p = profits, cap = 30) 

i error

error in f[, k] <- g :    number of items replace not multiple of replacement length in addition: warning message: in pmax(g, h) : argument fractionally recycled 

but when run smaller sized vectors, like

weights <- 1:20 profits <- 1:20 knapsack(w = weights, p = profits, cap = 30) 

it runs fine. knapsack() slow down (and prevent running) larger sets? i'm looking use lengths in thousands eventually.

this issue passing elements weight exceeding total capacity. see issue, let's @ first few lines of knapsack function:

function (w, p, cap)  {     n <- length(w)     x <- logical(n)     f <- matrix(0, nrow = cap + 1, ncol = n)     g <- matrix(0, nrow = cap + 1, ncol = 1)     (k in 1:n) {         f[, k] <- g         h <- c(numeric(w[k]), g[1:(cap + 1 - w[k]), 1] + p[k])         g <- pmax(g, h)     } 

when iteratively filling f matrix 1 column @ time, algorithm creates vector h following command (and computing pmax(g, h)):

h <- c(numeric(w[k]), g[1:(cap + 1 - w[k]), 1] + p[k]) 

numeric(w[k]) has length w[k], , when w[k] <= cap, g[1:(cap + 1 - w[k]), 1] + p[k] has length cap + 1 - w[k], meaning entire vector h has length cap+1, matching size of g. on other hand, when w[k] == cap + 1 end h vector of size cap+2, doesn't match size of g , gives trouble, , w[k] > cap + 1 error mixing positive , negative indices.

getting example function call, have weights 50 capacity of 30, yielding error:

weights <- 1:50 profits <- 1:50 knapsack(w = weights, p = profits, cap = 30) # error in f[, k] <- g :  #   number of items replace not multiple of replacement length # in addition: warning message: # in pmax(g, h) : argument fractionally recycled 

however when limit elements weight not exceeding capacity, no errors:

knapsack(w = weights[weights <= 30], p = profits[weights <= 30], cap = 30) # $capacity # [1] 30 #  # $profit # [1] 30 #  # $indices # [1] 1 2 3 4 5 7 8 

it ideal if knapsack function gracefully removed object weight exceeding capacity (since no such elements ever used in feasible solution) , gave solution code posted, workaround remove them input knapsack function.


Comments