Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var coins = [ // ordered by value (high->low) to ease looping
- ["ref", 19, 1], // format: ["name", count, worth]
- ["rec", 1, 0.33],
- ["scrap", 4, 0.11]
- ];
- function pickCoins(coins, target) {
- var picked = {};
- var remainder = target;
- // for every coin, starting with the most expensive...
- for (var i = 0; i < coins.length; ++i) {
- var name = coins[i][0],
- count = coins[i][1],
- worth = coins[i][2];
- picked[name] = picked[name] || 0;
- // ... ignore if we can't pick it ...
- if (picked[name] >= count) { continue; }
- // ... then check how many times we can pick it.
- // This is either limited by the amount of coins left, or the remainder
- var picks = Math.min(count - picked[name], Math.floor(remainder / worth));
- // Finally update stuff
- picked[name] = picked[name] + picks;
- remainder -= picks * worth;
- }
- return {coins: picked, remainder: remainder};
- }
Add Comment
Please, Sign In to add comment