I have all this variables declared:
var toReturn = 96.74
var myBank = 335.409
var typeofCoin = [0.01,0.05,0.10,0.25,1,5,10,20,100]
var quantityeachCoin = [ 1.01, 2.05, 3.1, 4.25, 90, 55, 20, 60, 100 ]
var quantityofCoins = [ 101, 41, 31, 17, 90, 11, 2, 3, 1 ]
var cidtoReturn = [["PENNY", 0], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE",0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]
What I´m hoping for with the following code is to return the variable cidtoReturn populated with the exact money in toReturn variable, from biggest coin to smallest. The ideal output would be this:
cidtoReturn = [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]
As you can see if you sum each of this values on this array the result it´s 96.74
So this is my approach:
-before anything I create reference value as a “stop”
–First I do a for loop to iterate through the coins. Loop it´s backward to be iterating from biggest coin to smallest.
–Second I make a counter variable to be sure I don´t use more coins of each typeofcoin available (for example, I can´t use more than 3 times the 20$ coin because I only have 3 coins of 20$ as you can see in the variable “quantityofCoins”)
From that point and once inside the nested for loop, I think a while loop would work. I want to put “while reference hasn´t reached 96.74…do the nested loop” when it has reached stop the loop. I do not know how to do this. I keep getting unexpected results now matter what modifications I do.
var reference = 0 //stop loop when reference value becomes 96.74
for (var i=cidtoReturn.length; i > -1; i--){
let counter = quantityofCoins[i]
for (var j=0; j<counter;j++){
cidtoReturn[i][1] += typeofCoin[i]
reference += typeofCoin[i]
}
}
Last test I got an infinite loop in my machine.