Skip to content

Instantly share code, notes, and snippets.

@headquarters
Created November 28, 2018 19:33
Show Gist options
  • Select an option

  • Save headquarters/561cdc06e6957d7d5177d238c1177fd2 to your computer and use it in GitHub Desktop.

Select an option

Save headquarters/561cdc06e6957d7d5177d238c1177fd2 to your computer and use it in GitHub Desktop.
const maxWeight = 50;
const piles = [
{
count: 60,
weight: 10
},
{
count: 120,
weight: 30
},
{
count: 100,
weight: 20
}
];
let bucket = [];
function getBucketWeight(bucket) {
return bucket.reduce((weight, pile) => { return weight + pile.weight }, 0);
}
function getBucketCount(bucket) {
return bucket.reduce((count, pile) => { return count + pile.count }, 0);
}
piles.forEach((pile) => {
pile.ratio = pile.count / pile.weight;
});
piles.sort((a, b) => {
if (a.ratio < b.ratio) {
return -1;
}
if (a.ratio > b.ratio) {
return 1;
}
return 0;
});
piles.forEach((pile) => {
if (getBucketWeight(bucket) + pile.weight <= maxWeight) {
bucket.push(pile);
}
});
console.log(`Bucket weighs ${getBucketWeight(bucket)} with ${getBucketCount(bucket)} rocks.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment