I need most efficiency logic for returning cash for change?
Just some “pseudo” explanation…
Here is a pseudo answer that will get you past the tests
// var changeOwed = difference between cash given and price
// loop through your cash register array and sum up the total dollar amount of all the money you have in your drawer
// if total is less than changeOwed return insufficient funds
// else if total === changeOwed then return Closed
// else calculate change owed by doing the following
// find the biggest possible change that you have available that is below the changeOwed
// subtract this amount from changeOwed
// add this amount to your array of payments
// subtract this amount from your cash drawer (so if $1 is the highest amount then take $1 out of cash drawer
// repeat until you have gone through the smallest coin you have available in your cash drawer
// if after going through all coins you find that your changeOwed is > $0.00 then return insuffient funds
// else if changeOwed is $0.00 then return your array of coins you will give as change
Hope that helps.
What is wrong with this penny, all the other tests works but this one, here is code:
function checkCashRegister(price, cash, cid) {
var change;
change = cash - price;
if ( change === getSum(cid) )
return "Closed";
var changeForMaAm = [];
for( var i = cid.length - 1; i >= 0; i -- ){
var offset = getDivider(cid[i][0], cid[i][1]);
var valueToReturn = 0;
for ( var y = 0 ; y < offset[0]; y ++ ){
if ( change - offset[1] < 0 )
break;
else {
change -= offset[1];
valueToReturn+= offset[1];
}
}
if ( valueToReturn !== 0)
changeForMaAm.push([cid[i][0], valueToReturn]);
if ( change === 0 )
break;
valueToReturn = 0;
}
/* COMMENT THIS FOR THIS TEST, BECAUSE THERE IS REST OF MONEY SOMETHING VERY SMALL
if ( change > 0 )
return "Insufficient Funds";
*/
// Here is your change, ma'am.
return changeForMaAm;
}
function getSum(cid){
var total = 0;
for ( var i = 0; i < cid.length; i ++ ){
total += cid[i][1];
}
return total;
}
// return sum div name, and name in digit
function getDivider(name, value){
switch(name){
case "ONE HUNDRED":
return [value / 100, 100];
case "TWENTY":
return [value / 20, 20];
case "TEN":
return [value / 10, 10];
case "FIVE":
return [value / 5, 5];
case "ONE":
return [value, 1];
case "QUARTER":
return [value / 0.25, 0.25];
case "DIME":
return [value / 0.1, 0.10];
case "NICKEL":
return [value / 0.05, 0.05];
case "PENNY":
return [value / 0.01, 0.01];
default:
console.log("Error");
}
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME",
3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]
checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);