多重背包问题

function PackageItem(name, weight, value, count) {
    this.name = name;
    this.weight = weight;
    this.value = value;
    this.count = count;
}

function get01PackageAnswerFor2degree(bagItems, bagsize, countForItem) {
    var bagMatrix = [];
    var item;
    var answers = [];

    for (var i = 0; i <= bagItems.length; i++) {
        bagMatrix[i] = [];
        for (var j = bagsize; j >= 0; j--) {
            bagMatrix[i][j] = [];
            answers[j] = [];
            for (var k = countForItem; k >= 0; k--) {
                bagMatrix[i][j][k] = 0;
                answers[j][k] = [];
            }
        }
    }

    for (var tmpBagsize = 1; tmpBagsize <= bagsize; tmpBagsize++) {
        for (var tmpCount = 1; tmpCount <= countForItem; tmpCount++) {
            for (var tmpItemID = 0; tmpItemID < bagItems.length; tmpItemID++) {
                item = bagItems[tmpItemID];
                if (item.weight > tmpBagsize) {
                    if (tmpItemID == 0) {
                        bagMatrix[tmpItemID][tmpBagsize][tmpCount] = 0;
                    } else {
                        bagMatrix[tmpItemID][tmpBagsize][tmpCount] = bagMatrix[tmpItemID - 1][tmpBagsize][tmpCount];
                    }
                } else {
                    if (item.count > tmpCount) {
                        if (tmpItemID == 0) {
                            bagMatrix[tmpItemID][tmpBagsize][tmpCount] = 0;
                        } else {
                            bagMatrix[tmpItemID][tmpBagsize][tmpCount] = bagMatrix[tmpItemID - 1][tmpBagsize][tmpCount];
                        }
                    } else {
                        var itemInBag;
                        if (tmpItemID == 0) {
                            bagMatrix[tmpItemID][tmpBagsize][tmpCount] = item.value;
                            continue;
                        } else {
                            itemInBag = bagMatrix[tmpItemID - 1][tmpBagsize - item.weight][tmpCount - item.count] + item.value; //向上向下找都无所谓,只要安一定的顺序找就行了
                            bagMatrix[tmpItemID][tmpBagsize][tmpCount] = Math.max(bagMatrix[tmpItemID - 1][tmpBagsize][tmpCount], itemInBag); //比较下现在的情况是不是比不动要好 0+6 < 7 就不
                        }

                        
                    }
                }
            }
        }
    }

    return bagMatrix[bagItems.length - 1][bagsize][countForItem];
}

var nameArr = ['a', 'b', 'c', 'd', 'e'];
var weightArr = [3, 2, 6, 5, 4];
var valueArr = [6, 3, 13, 4, 6];
var countArr = [1, 1, 1, 1, 1]


var bagItems = [];

for (var i = 0; i < nameArr.length; i++) {
    var bagItem = new PackageItem(nameArr[i], weightArr[i], valueArr[i], countArr[i]);
    bagItems[i] = bagItem;
}
let answ = get01PackageAnswerFor2degree(bagItems, 11, 3);

console.log(answ);

你可能感兴趣的:(多重背包问题)