-3

I am trying to make a function that chooses which coins should be used in a certain situation:

-

Kinds of Coins:

Coin worth 1

Coin worth 0.33

Coin worth 0.11

-

The amount of each coin should be limited, so in the function you should be able to declare how many coins and which kind of coin is being used. Fractaly already answered this question partially, I just don't get how I could implement a system that would also look at the amount of coins. Help is appreaciated a lot!

Thanks in advance!

timgfx
  • 1
  • 1
  • 3
    Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Right now, the question reads as a "write this code for me." Make an attempt to solve the problem, and *if* you run into a problem doing it, and do your research and look for answers and don't find them, then post a question about that specific problem. – T.J. Crowder Jun 25 '16 at 21:29
  • This problem is called a system of equations See [this](http://stackoverflow.com/questions/22260352/solve-set-of-linear-equations-with-javascript) post – user31415 Jun 25 '16 at 21:32

1 Answers1

1

Since your coins are integer multiples of eachother, you can simply take a greedy approach, selecting the largest coins first. So for 3.44 for instance, you would select 3 coins worth 1, (3 / 1 round down = 3). The remainder (3.44 - 3 = 0.44) still requires smaller coins. Proceed in the same way (0.44 / 0.33 = 1, remainder 0.11) then (0.11 / 0.11 = 1) to find the smaller denominations. In javascript:

var denominations = [1, 0.33, 0.11]; // must be sorted
var targetQuatity = 3.44;
pickCoins(denominations, targetQuantity);

function pickCoins(denominations, targetQuantity) {
    var remainder = targetQuantity;
    var coinsPicked = {};
    for (var i = 0; i < denominations.length; i++) {
        var denomination = denominations[i];
        coinsPicked[denomination] = Math.floor(remainder / denomination);
        remainder -= coinsPicked[denomination] * denomination;
    }
    return coinsPicked;
}
Fractaly
  • 834
  • 2
  • 10
  • 25
  • Alright, I get it! Thanks a lot. For implementing being able to only use a limited amount of coins I think I will do this: Store an object of objects(so it can be used by multiple people at a time) with the amount of coins, then in the function it will decrease the amount of coins of the type that had been used, and if it is 0 it can't be used anymore! I think that will work, thanks a lot for the quick response, you're awesome :) – timgfx Jun 25 '16 at 21:40
  • I just tried implementing the limited amount of coins thing, but I couldn't figure it out :/. More help would really help ;) – timgfx Jun 25 '16 at 21:46