function fractionalKnapsack(fruits, capacity) {
fruits.sort((a, b) => (b.value / b.weight) - (a.value / a.weight));
let totalValue = 0;
let strategy = [];
for (const fruit of fruits) {
if (capacity > 0 && fruit.weight <= capacity) {
capacity -= fruit.weight;
totalValue += fruit.value;
strategy.push({ name: fruit.name, weight: fruit.weight });
} else {
totalValue += fruit.value * (capacity / fruit.weight);
strategy.push({ name: fruit.name, weight: capacity });
break;
}
}
return { totalValue, strategy };
}
const fruits = [
{ name: '苹果', weight: 15, value: 300 },
{ name: '香蕉', weight: 18, value: 180 },
{ name: '橘子', weight: 10, value: 150 },
{ name: '猕猴桃', weight: 9, value: 270 }
];
const capacity = 20;
const result = fractionalKnapsack(fruits, capacity);
console.log("Total value:", result.totalValue);
console.log("Strategy:", result.strategy);