user11369290
user11369290

Reputation:

don't know how to solve this exercice

I must calculate the exchange rate, in legal tender, for an exact amount. The exact paper money and coins must be inserted into an array. I am stuck in this step and do not know how to solve it.

function countChange(amount) {
    const currency = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
    const change = [];

    for (let i = 0; i < currency.length; i++) {
        const value = currency[i];
        if (value <= amount) {
            change.push(value)
        }

    }
    return change;

};


console.log(countChange(500.26));

Upvotes: 0

Views: 67

Answers (2)

Baka
Baka

Reputation: 23

I think this might be what you're expecting :

function countChange(amount) {
    const currency = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
    const change = [];
    var changed = 0;
    while(changed < amount){
        for(var i = 0; i < currency.length; i++){
            if(amount-currency[i] >= 0){
                change.push(currency[i]);
                changed+=currency[i];
                amount-=currency[i];
            }
        }
    }
    return change;

}

console.log(countChange(500.26))

Upvotes: 0

Keith
Keith

Reputation: 24181

Below is simple example.

Just simply iterate for each coinage size, just divide the current total amount by each coinage size, if there is any coinage then push this into an array.

function countChange(amount) {
    const currency = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
    const change = [];
    for (let i = 0; i < currency.length; i++) {
        const coinsize = currency[i];
        //how many coins?
        const coins = Math.trunc(amount / coinsize);
        //remove these from total
        amount -= coinsize * coins;
        //fix rounding problems.
        amount = Math.round(amount * 100) / 100;
        //add to our result
        if (coins > 0)
        {
            change.push({
                coinsize,
                coins
            });
        }
    }
    return change;
};


console.log(countChange(500.26));

Upvotes: 1

Related Questions