Created
November 28, 2018 19:33
-
-
Save headquarters/561cdc06e6957d7d5177d238c1177fd2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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