Skip to content

Instantly share code, notes, and snippets.

@abhisekp
Last active April 4, 2018 06:51
Show Gist options
  • Save abhisekp/3ce615f8933ffa92994a28ee0d6b0fdd to your computer and use it in GitHub Desktop.
Save abhisekp/3ce615f8933ffa92994a28ee0d6b0fdd to your computer and use it in GitHub Desktop.
Package Problem from CodeEval

Package Problem

Package Problem

You want to send your friend a package with different things. Each thing you put inside the package has such parameters as index number, weight and cost. The package has a weight limit. Your goal is to determine which things to put into the package so that the total weight is less than or equal to the package limit and the total cost is as large as possible.

You would prefer to send a package which weights less in case there is more than one package with the same price.

https://www.codeeval.com/open_challenges/114/

const fs = require('fs');
function decreasingProductCostWithLowerWeight(productA, productB) {
if (productA.cost === productB.cost) {
return productA.weight - productB.weight;
}
return productB.cost - productA.cost;
}
function weightLessThan(weight) {
return product => product.weight < weight;
}
function parseProductString(productStr) {
const productArr = productStr.match(/\d+(\.\d+)?/g).map(Number);
const index = productArr[0];
const weight = productArr[1];
const cost = productArr[2];
return {
cost,
weight,
index,
};
}
fs
.readFileSync(process.argv[2], 'utf-8')
.trim()
.split('\n')
.map((line) => {
// max weight that can be carried in a box
const lineSplits = line.split(':');
const MAX_WEIGHT = Number(lineSplits[0]);
// console.log('Maximum Weight:', MAX_WEIGHT);
const productsString = lineSplits[1].trim().split(' ');
// console.log('Products String:', productsString);
const products = productsString.map(parseProductString);
// console.log('Products:', products);
const validProducts = products.filter(weightLessThan(MAX_WEIGHT));
// console.log('Valid Products: ', validProducts);
return {
maxWeight: MAX_WEIGHT,
products: validProducts,
};
})
.forEach(({ maxWeight, products }) => {
// do something with each package
if (products.length === 0) {
console.log('-');
}
// sort products by cost (high to low)
const productsByCost = products.sort(decreasingProductCostWithLowerWeight);
const { indexes } = productsByCost.reduce(
(acc, product) => {
// eslint-disable-next-line prefer-destructuring, no-shadow
const indexes = acc.indexes;
// eslint-disable-next-line prefer-destructuring
const totalWeight = acc.totalWeight;
const predictedWeight = product.weight + totalWeight;
if (predictedWeight <= maxWeight) {
indexes.push(product.index);
return {
...acc,
indexes,
totalWeight: predictedWeight,
};
}
return acc;
},
{
indexes: [],
totalWeight: 0,
},
);
// at the end, log the indexes
const productIndexesStr = indexes.join(',');
console.log(productIndexesStr);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment