0
我想解決使用動態規劃的Scala中的揹包問題。作爲需求的一部分,我還需要顯示哪些項目被挑選填充到Knapsack.But中,但我得到「ArrayIndexOutOfBoundException」。 到目前爲止我有什麼代碼如下:Knapsack中的ArrayIndexOutofBoundsException Scala
availableMoney is equivalent to weight of knapsack.products.channels is equivalent to value[] in knapsack.products.price is equivalent to weight[] in knapsack.
def knapSack(availableMoney: Int, products: List[Product]) : Int = {
var wt = List[Int](products.length)
var value = List[Int](products.length)
for (product <- products) {
value ::= product.channels.length
wt ::= product.price
}
val matrix = Array.fill(2, 2)(0)
val picks = Array.fill(2, 2)(0)
for (i <- 1 to products.length){
for (j <- 0 to availableMoney){
if (wt(i-1)<=j){
matrix(i)(j) = max(matrix(i-1)(j),value(i-1)+matrix(i-1)(j-wt(i-1)));
if (value(i-1)+matrix(i-1)(j-wt(i-1))>matrix(i-1)(j))
picks(i)(j)= 1;
else
picks(i)(j)= -1;
}
else{
picks(i)(j) = -1;
matrix(i)(j) = matrix(i-1)(j);
}
}
}
matrix(products.length)(availableMoney)
}
你在哪裏得到例外? – Carcigenicate
'for(i < - 1 to products.length)'應該可能是'for(i < - 1 to(products.length - 1))'。我不記得一個範圍內的最大值是否是唯一的。 – Carcigenicate
運算符'to'是Range.Inclusive,而'until'是Range.Exclusive。如果您使用IDE並將鼠標懸停在這些運算符上,則會看到說明(包含/排除)。所以它可能應該是'直到products.length' – radumanolescu