【问题标题】:R mknapsack functionR 背包功能
【发布时间】:2018-11-26 20:57:27
【问题描述】:

我从 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

【问题讨论】:

    标签: r rstudio knapsack-problem


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 2016-06-18
      • 2013-03-30
      • 2015-04-08
      • 1970-01-01
      • 2018-03-30
      • 2019-11-13
      • 2013-06-18
      相关资源
      最近更新 更多