Search code examples
javascriptalgorithmcoin-change

Coins changing algorithm problem - not working


I'm using the following algorithm for coins changing problem:

for (let coin of coins){
    if(change >= coin){
        if (Math.floor(change/coin) > 0){
            console.log(Math.floor(change/coin)+ " pièces de " + coin + " euro");
            let newChange = change - coin;
            change = newChange;
        }
    }
 }

The result should look like below:

Purchase of €1.34 paid for with €5:
Change: €3.66 
Coins returned:
2 euro: 1 
1 euro: 1
50 cents: 1 
10 cents: 1 
5 cents: 1 
1 cent: 1

My results look like this:

Purchase of $1.34 paid for with $5
Change: 3.66
1 pièces de 2 euro
1 pièces de 1 euro
1 pièces de 0.5 euro
1 pièces de 0.1 euro
1 pièces de 0.05 euro
1 pièces de 0.01 euro

Solution

  • Notice that your line: let newChange = change - coin; is wrong as it assume only 1 coin has been given and ignore case of multi coins.

    New assignment to change var should be the modulo of the change after reduce the coin so change your if to:

    if (Math.floor(change/coin) > 0){
        console.log(Math.floor(change/coin)+ " pièces de " + coin + " euro");
        change  = change % coin;
    }