Guest User

Untitled

a guest
Jun 26th, 2016
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var coins = [ // ordered by value (high->low) to ease looping
  2.   ["ref", 19, 1], // format: ["name", count, worth]
  3.   ["rec", 1, 0.33],
  4.   ["scrap", 4, 0.11]
  5. ];
  6. function pickCoins(coins, target) {
  7.   var picked = {};
  8.   var remainder = target;
  9.  
  10.   // for every coin, starting with the most expensive...
  11.   for (var i = 0; i < coins.length; ++i) {
  12.     var name = coins[i][0],
  13.         count = coins[i][1],
  14.         worth = coins[i][2];
  15.    picked[name] = picked[name] || 0;
  16.  
  17.     // ... ignore if we can't pick it ...
  18.     if (picked[name] >= count) { continue; }
  19.  
  20.     // ... then check how many times we can pick it.
  21.     // This is either limited by the amount of coins left, or the remainder
  22.     var picks = Math.min(count - picked[name], Math.floor(remainder / worth));
  23.  
  24.     // Finally update stuff
  25.     picked[name] = picked[name] + picks;
  26.     remainder -= picks * worth;
  27.   }
  28.  
  29.   return {coins: picked, remainder: remainder};
  30. }
Add Comment
Please, Sign In to add comment