编辑代码

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()