function main() {
const fruits = [
{ name: '苹果', weight: 15, value: 300 },
{ name: '香蕉', weight: 18, value: 180 },
{ name: '橘子', weight: 10, value: 150 },
{ name: '猕猴桃', weight: 9, value: 270 }
];
const strategy = [];
let totalValue = 0;
function packWithFruit(maxWeight) {
fruits.sort((a, b) => (b.value / b.weight) - (a.value / a.weight));
let currentWeight = 0;
for (let fruit of fruits) {
if (currentWeight + fruit.weight <= maxWeight) {
strategy.push({ name: fruit.name, weight: fruit.weight, value: fruit.value });
currentWeight += fruit.weight;
totalValue += fruit.value;
} else {
const remainingWeight = maxWeight - currentWeight;
const fraction = remainingWeight / fruit.weight;
const partialValue = fraction * fruit.value;
strategy.push({ name: fruit.name, weight: remainingWeight, value: Math.round(partialValue) });
totalValue += partialValue;
break;
}
}
}
packWithFruit(20)
console.log('装水果的策略:');
for (let item of strategy) {
console.log(`${item.name},重量:${item.weight}kg,价值:${item.value}元`);
}
console.log(`总价值:${totalValue}元`);
}
main()