SOURCE

//部分背包问题:每件物品是可再分的,即允许将某件物品的一部分(例如 1/3)放入背包

//首先根据收益率进行物品排序,然后按顺序装满即可

function sort(w,p){
    let income = {}
    let len = w.length
    for(let i = 0;i<len;i++){
        income[i]=p[i]/w[i]
    }
    for (i = 0; i < len; i++) {
        for (j = i + 1; j < len; j++) {
            if (income[i] < income[j]) {
                temp = income[i];
                income[i] = income[j];
                income[j] = temp;

                temp = w[i];
                w[i] = w[j];
                w[j] = temp;

                temp = p[i];
                p[i] = p[j];
                p[j] = temp;
            }
        }
    }
}

function partBackpack(weight,price,max){
    //记录每个物品的比例
    let result = {}
    let index = 0
    let maxPrice = 0
    sort(weight,price)
    while(max){
        temp = max> weight[index]? weight[index]:max
        result[index] = temp / weight[index]
        max -= temp
        index++
    }
    console.log('商品的比例:')
    for(let key in result){
        console.log(`${weight[key]}:${result[key]}`)
        maxPrice+=weight[key]*result[key]*price[key]
    }
    console.log("最高总价为:"+maxPrice)
    return maxPrice
}

let weight = [10,30,20]
let price = [60,100,120]
let Max = 50
partBackpack(weight,price,Max)

console 命令行工具 X clear

                    
>
console