I'm trying to find out the possible coins of given amount according to **denominators **as arguments. I iterate over the the denominators and did comparisons. but the output is not expected as i want.
function amountTocoins(amount, denominations){
let possibleCoins = [];
for(let i=0; i<denominations.length; i++){
let coin = denominations[i];
while(amount >= coin){
possibleCoins.push(coin);
amount -= coin;
}
if(amount === 0){
break;
}
}
return possibleCoins;
}
console.log(amountTocoins(46, [25, 10, 5, 2, 1]));
Output should be [25, 10, 10] which is equal to denominator array [25, 10, 5, 2, 1]. because last iteration ends with 1.and we have no more element for comparison.
As run the code, it gives me [25, 10, 10, 1] as output. why ?