我正在编写一个程序,使用背包解决方案找到最佳的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};
};
我是否犯了一个我没有看到的明显错误,或者我的逻辑完全脱离了?
答案 0 :(得分:1)
您正在检查解决方案集吗?接受位置的逻辑不包含在背包逻辑中,这意味着解决方案集是背包解决方案之上的过滤器。你确实到达了正确的背包解决方案,但是因为,在解决方案的基础上,你正在检查位置是否已经填满,从解决方案集中消除了一些项目(争夺相同位置的项目)和总重量降低。