Javascript Coin changing / Change making algorithm

前端 未结 3 808
误落风尘
误落风尘 2021-01-25 19:24

So I\'ve been trying to create a program in Javascript/jQuery that splits an amount of money into the smallest amount of dollar bills. So far the program only works with one bil

3条回答
  •  离开以前
    2021-01-25 19:48

    In a more compacted way:

    function moneyChanger(money, bills){
        if (bills[0] < bills[1]) bills.reverse();
        const change = {};
        bills.map(b => {
           change[b] = Math.floor(money/b);
           money -= b*change[b];
        }) 
        return change
    }
    
    ...
    
    var change = moneyChanger(2995,[5,10,20,50,100,200,500])
    

    The result for this example:

    {5:1, 10:0, 20:2, 50:1, 100:0, 200:2, 500:5}
    

提交回复
热议问题