|
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); |
|
}); |