编辑代码

class Commodity {
    constructor(name, weight, value) {
        this.name = name;
        this.value = value;
        this.weight = weight;
    }
}

function getMaxValueForBackpack(capacity, commodities) {
    let maxValue = -1;
    let maxValuePos = -1;

    // 用二进制表示要循环的次数 ,例如2的三次方 === 8
    for (let i = 0; i < Math.pow(2, commodities.length); i++) {
        let pos = i;
        let weight = 0;
        let value = 0;
        let curBit = 0;

        while (pos > 0) {
            if ((pos & 1) === 1) {
                weight += commodities[curBit].weight;
                value += commodities[curBit].value;
            }
            pos = pos >> 1;
            curBit++;
        }
    
        // 循环过后,找出最大的
        if (weight <= capacity && maxValue < value) {
            maxValue = value;
            maxValuePos = i;
        }
            console.log("循环过后的值:",weight,value)
            console.log("最大值:",maxValue,maxValuePos)
    }


// 输出结果
    if (maxValuePos > 0) {
        let curBit = 0;
        console.log("I want to put:");
        while (maxValuePos > 0) {
            if ((maxValuePos & 1) === 1) {
                console.log(commodities[curBit].name + "(" + commodities[curBit].weight + "," + commodities[curBit].value + ")");
            }
            maxValuePos = maxValuePos >> 1;
            curBit++;
        }
    }
}

const commodities = [
    new Commodity("吉他", 15, 1500),
    new Commodity("笔记本电脑", 20, 2000),
    new Commodity("音响", 30, 3000)
];

getMaxValueForBackpack(35, commodities);

const fourCommodities = [
    new Commodity("吉他", 15, 1500),
    new Commodity("笔记本电脑", 20, 2000),
    new Commodity("音响", 30, 3000),
    new Commodity("苹果手机", 10, 2000)
];

getMaxValueForBackpack(40, fourCommodities);