Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate total price of items that fit within weight and size limits of a suitcase

A salesperson who walks door to door to sell goods carries a suitcase with him. Each morning he packs his suitcase with items from his inventory. Each item has a size (cm3), price (Rs) and weight (grams). Write a javascript programme to calculate the total price of the items he can carry in his suitcase without exceeding the max weight and size limits of the suitcase.

Products list:

Item 01: weight: 10, price: 20, size: 30
Item 02: weight: 15, price: 25, size: 35
Item 03: weight: 20, price: 30, size: 40
Item 04: weight: 25, price: 35, size: 40

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Test 01

Inputs: maxWeight = 50, maxSize = 50

Expected Output: Total price: 35

Test 02

Inputs: maxWeight = 30, maxSize = 100

Expected Output: Total price: 50

They have provided this code snippets for me :


function getTotalPrice(items, curWeight, curSize, curIndex) {
  return false;
}

const itemList = [
{ weight: 10, price: 20, size: 30 },
{ weight: 15, price: 25, size: 35 },
{ weight: 20, price: 30, size: 40 },
{ weight: 25, price: 35, size: 40 }
];

getTotalPrice(itemList, 50, 50, itemList.length);

I wrote this programme but its only reading and give 35 for the first test. It is correct but ot working for test 2. Please help me with this

function getTotalPrice(items, curWeight, curSize, curIndex) {
  const maxWeight = curWeight;
  const maxSize = curSize;
  let totalPrice = 0;

  for (let i = 0; i < items.length; i++) {
    const item = items[i];

    if (item.weight <= maxWeight && item.size <= maxSize) {
      totalPrice = item.price;
    }
  }
  console.log(totalPrice);
  return totalPrice;
}

const itemList = [
  { weight: 10, price: 20, size: 30 },
  { weight: 15, price: 25, size: 35 },
  { weight: 20, price: 30, size: 40 },
  { weight: 25, price: 35, size: 40 },
];

getTotalPrice(itemList, 50, 50, itemList.length);

>Solution :

This looks like Knapsack problem, and that too a 0/1 Knapsack.

I can solve it, but it would be better if you go through this algorithm and answer the question yourself.

You will learn this new algorithm, and an optimized way to solve it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading