Hey All!
I’ve been stuck on this problem for some time.
Had a weird bug with getting weird decimal numbers. This seems to have been resolved using an extra function to round answers to two decimal places explicitly.
Now I have a working solution that satisfies and completes all answers except one. (I get the correct answer but it won’t give me a check mark…)
Givens: 19.50, 20.00, [[“PENNY”, 0.01], [“NICKEL”, 0], [“DIME”, 0], [“QUARTER”, 0], [“ONE”, 0], [“FIVE”, 0], [“TEN”, 0]
Expected: “Insufficient Funds” - I get this exact answer but it would not let me pass all other tests have been passed.
Full code below. (Sorry rather lengthy)
function checkCashRegister(price, cash, cid) {
function roundMe(number) {
number *= 100;
number = Math.round(number);
number /= 100;
return number;
}
var change = cash-price;
var answer;
var changes = [1/100, 5/100,1/10,1/4,1,5,10,20,100];
var totalChange = 0;
var array = [];
var currentArray =[0,0];
// check for the two bad scenarios.
for (var i=0; i<cid.length; i++){
totalChange += cid[i][1];
}
if (totalChange < change){
return “Insufficent Funds”;
}
else if (totalChange == change){
return “Closed”;
}
//main program
else {
//read through the cid from biggest to smallest.
for (var i= cid.length-1; i>=0; i–){
if (changes[i]<= change && cid[i][1]>0 && change >0){
currentArray[0] = cid[i][0];
// if we require more change than what is available in correct basket then we take the entire pot of correct.
if (roundMe(change) >= cid[i][1]) {
currentArray[1] = roundMe(cid[i][1]);
change = change-cid[i][1];
change = roundMe(change);
}
else {
//keep taking out of the basket UNTIL the correct change no longer becomes the correct change.
while (roundMe(change) >= roundMe(changes[i])){
currentArray[1] += roundMe(changes[i]);
change -= roundMe(changes[i]);
cid[i][1] -= roundMe(changes[i]);
}
}
}
if (currentArray[1]>0){
array.push(currentArray);
}
currentArray = [0,0];
}
// Last insufficient funds checker.
if (roundMe(change)>0){
return “Insufficient Funds”;
}
else{answer = array;}
}
// Here is your change, ma’am.
return answer;
}
Test Below.
checkCashRegister(19.50, 20.00, [[“PENNY”, 0.01], [“NICKEL”, 0], [“DIME”, 0], [“QUARTER”, 0], [“ONE”, 0], [“FIVE”, 0], [“TEN”, 0], [“TWENTY”, 0], [“ONE HUNDRED”, 0]]);