R背包功能

时间:2018-11-26 20:57:27

标签: r rstudio knapsack-problem

我从article运行R程序,其中使用了adagio软件包中的mknapsack函数,一切都很好。但是,如果我想使用随机值,则会出现错误“错误条件升高”。

我有一个程序:

n=16
m=5
max=700
min = 10

planks_we_have = floor(runif(n=m, min = 100, max = max))
planks_we_want = floor(runif(n=n, min = min, max = 16))

library(adagio)
# mknapsack calling signature is: mknapsack(values, weights, capacities)
solution <- mknapsack(planks_we_want, planks_we_want, planks_we_have)
# Above I added +1 cm  to each length to compensate for the loss when sawing.
solution$ksack
# Now pretty printing what to cut so that we don't make mistakes...
assignment <- data.frame(cut_this = planks_we_have[solution$ksack], into_this = planks_we_want)
t(assignment[order(assignment[,1]), ])

结果:

Warning
In mknapsack(planks_we_want, planks_we_want, planks_we_have) :
  Error condition raised: check input data ...!

Error
In data.frame(cut_this = planks_we_have[solution$ksack], into_this = planks_we_want) :
  Arguments imply different numbers of lines: 0, 5

我不明白是什么原因。背包功能的源代码没有给我任何帮助:

function (p, w, k, bck = -1) 
{
    stopifnot(is.numeric(p), is.numeric(w), is.numeric(k))
    if (any(w <= 0)) 
        stop("'weights' must be a vector of positive numbers.")
    if (any(p <= 0)) 
        stop("'profits' must be a vector of positive numbers.")
    if (any(floor(p) != ceiling(p)) || any(floor(w) != ceiling(w)) || 
        any(floor(k) != ceiling(k)) || any(p >= 2^31) || any(w >= 
        2^31) || any(k >= 2^31)) 
        stop("All inputs must be positive integers < 2^31 !")
    n <- length(p)
    m <- length(k)
    if (length(w) != n) 
        stop("Profit 'p' and weight 'w' must be vectors of equal length.")
    xstar <- vector("integer", n)
    vstar <- 0
    num <- 5 * m + 14 * n + 4 * m * n + 3
    wk <- numeric(n)
    iwk <- vector("integer", num)
    S <- .Fortran("mkp", as.integer(n), as.integer(m), as.integer(p), 
        as.integer(w), as.integer(k), bs = as.integer(bck), 
        xs = as.integer(xstar), vs = as.integer(vstar), as.numeric(wk), 
        as.integer(iwk), as.integer(num), PACKAGE = "adagio")
    if (S$vs < 0) 
        warning("Error condition raised: check input data ...!")
    return(list(ksack = S$xs, value = S$vs, btracks = S$bs))
}

版本:

R - 3.4.1
Adagio - 0.7.1

1 个答案:

答案 0 :(得分:1)

如果您对某个功能有疑问,请先阅读帮助页面。查看返回的解决方案,它的错误代码为vs=-7,并显示“ vs = -7,如果数组k的排序不正确”。对容量向量进行排序可能会产生另一个错误,例如,如果所有物品都可以放在一个背包中。当然,所有这些都取决于生成的随机数(在询问之前最好固定随机数)。