我正在写一个程序来找到最好的MLB阵容使用背包解决方案。为此,我传入球员数据,其中包含球员计算值和薪水。薪水将是我的"重量",因为我是一个背包问题。
我的问题不是选择球员,而是选择最优阵容。我要选一个投手,一个中锋,一垒手,二垒手,三垒手,游击手和三个外野手。我可以成功地做到这一切。我希望我的"权重"是36,000,但我目前只选择了一个总数为21,000的阵容。
这是我的背包代码:
CalculateLineUp.prototype.findOptimalLineUp = function(data, capacity) {
var items = data.data;
var idxItem = 0,
idxCapSpace = 0,
idxPosition = 0,
oldMax = 0,
newMax = 0,
numItems = items.length,
weightMatrix = new Array(numItems+1),
keepMatrix = new Array(numItems+1),
positionArray = new Array("P", "C", "1B", "2B", "3B", "SS", "OF", "OF", "OF"),
solutionSet = [];
// Setup matrices
for(idxItem = 0; idxItem < numItems + 1; idxItem++){
weightMatrix[idxItem] = new Array(capacity+1);
keepMatrix[idxItem] = new Array(capacity+1);
}
// Build weightMatrix from [0][0] -> [numItems-1][capacity-1]
for (idxItem = 0; idxItem <= numItems; idxItem++){
for (idxCapSpace = 0; idxCapSpace <= capacity; idxCapSpace++){
// Fill top row and left column with zeros
if (idxItem === 0 || idxCapSpace === 0){
weightMatrix[idxItem][idxCapSpace] = 0;
}
// If item will fit, decide if there's greater value in keeping it,
// or leaving it
else if (items[idxItem-1]["Salary"] <= idxCapSpace){
newMax = items[idxItem-1]["Value"] + weightMatrix[idxItem-1][idxCapSpace-items[idxItem-1]["Salary"]];
oldMax = weightMatrix[idxItem-1][idxCapSpace];
// Update the matrices
if(newMax > oldMax ){
weightMatrix[idxItem][idxCapSpace] = newMax;
keepMatrix[idxItem][idxCapSpace] = 1;
}
else{
weightMatrix[idxItem][idxCapSpace] = oldMax;
keepMatrix[idxItem][idxCapSpace] = 0;
}
}
//Else, item can't fit; value and weight are the same as before
//else
//weightMatrix[idxItem][idxCapSpace] = weightMatrix[idxItem-1][idxCapSpace];
}
}
// Traverse through keepMatrix ([numItems][capacity] -> [1][?])
// to create solutionSet
idxCapSpace = capacity;
idxItem = numItems;
for(idxItem; idxItem < capacity; idxItem--){
if(keepMatrix[idxItem][idxCapSpace] === 1 && !this.filledAllPositions(items[idxItem - 1]["Position"])){
solutionSet.push(items[idxItem - 1]);
idxCapSpace = idxCapSpace - items[idxItem - 1]["Salary"];
}
}
return {"maxValue": weightMatrix[numItems][capacity], "set": solutionSet};
};
是我犯了一个明显的错误,我只是没有看到,还是我的逻辑完全错误?
您正在检查解决方案集,对吗?接受位置的逻辑不包含在背包逻辑中,这意味着solutionSet是位于背包解决方案之上的过滤器。您确实得到了正确的背包解决方案,但是因为在解决方案的顶部,您正在检查位置是否已经被填满,所以从解决方案集中消除了一些项目(争夺相同位置的项目)并且总重量减少了。