【问题标题】:Solving the algorithm question using javascript使用javascript解决算法问题
【发布时间】:2020-05-30 13:29:16
【问题描述】:

我不知道如何思考一个问题。因为我知道这里的人更有经验和指导,所以我想问你。如果你能解决问题并解释它,我将不胜感激。问题:

“想想你有无限数量的胡萝卜,但数量有限的胡萝卜种类。另外,你有一个可以容纳有限重量的袋子。每种胡萝卜都有重量和价格。写一个接受胡萝卜类型和容量并返回袋子可以容纳的最大值的函数。”

我不确定我是否完全理解这个问题,也不确定我该怎么做。如果你能帮助我,我会很高兴。

let carrotTypes = [{
    price: 100,
    kg: 2
  },
  {
    price: 120,
    kg: 4
  },
  {
    price: 80,
    kg: 7
  }
];

let bagCapacity = 36; //kg

getMaxValue(carrotTypes, bagCapacity)

function getMaxValue(carrotTypes, capacity) {

  carrotTypes.forEach(carrot => {
     console.log(carrot);
  });

}

【问题讨论】:

标签: javascript algorithm


【解决方案1】:

您可以采用蛮力方法并获取所有可能的 vcombinations 并返回总和最小的那个。

结果是一个包,其中包含给定数据的相同索引项的计数。

function getMaxValue(data, target) {
    function iter(index, bag, weight, total) {
        if (weight > target) return;
        if (weight === target) {
            if (!result || total < result.total) result = { bag, weight, total };
            return;
        }
        let temp = [...bag];
        temp[index]++;
        iter(index, temp, weight + data[index].kg, total + data[index].price);
        if (++index >= data.length) return;
        iter(index, bag, weight, total);
    }

    var result;
    iter(0, data.map(_ => 0), 0, 0);
    return result;
}

let carrotTypes = [{ price: 100, kg: 2 }, { price: 120, kg: 4 }, { price: 80, kg: 7 }],
    bagCapacity = 36,
    bag = getMaxValue(carrotTypes, bagCapacity);

console.log(bag);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    我建议你像这样建立你的想法。开始在较小的部分解决问题。如果你的包能承受 2 公斤的重量呢?

    为了更好地理解,我正在修改这些值。所以让我们假设你有 3 种胡萝卜类型

     let carrotTypes = [{
        price: 50,
        kg: 1
      },
      {
        price: 100,
        kg: 2
      },
      {
        price: 80,
        kg: 3
      }
    ];
    

    随机小号,让你感受一下,你的包能装3Kg。

    现在继续这个问题,假设袋子可以处理的最大重量为0,那么答案是什么,然后将最大重量一一增加。 另外,如果你只有一种胡萝卜怎么办,然后增加胡萝卜的种类。

    最大重量包可以处理

                 0       1       2        3
    (50)  1      0       50     100     150
    (100) 2      0       50     100     150
    (80)  3      0       50     100     150
    
    

    您可以选择是否选择该胡萝卜类型。 因此,如果您选择选择(仅当您可以,即 CarrotTypeWeight

    CarrotTypePrice + Answer(WeightBag 可以容纳 - CarrotTypeWeight) -> 在表格中向左移动

    如果你选择不选择

    Answer(WeightBag 没有这种类型的时候可以hold) -> 在表中向上移动

    我希望你能想象它。最后一个数字 matrix[n-1][n-1] 将是您的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      相关资源
      最近更新 更多