I am struggling on how to create a program to give adequate change to customers.The program should return the amount of notes and coins for the customer’s change.
Example: If the price is €3.75 and the paid amount is €50, then the client should receive €46.25 back in change.
The expected output should be:
2 x €20 // 2 twenty euro notes
1 x €5 // 1 five euro note
1 x €1 // 1 euro
1 x €0.2 // 1 twenty cent coin
1 x €0.05 // 1 five cent coin
Example: Price: €4.50, Paid amount: €20, Change: 15.50
Expected output:
1 x €10
1 x €5
1 x €0.5
Notes
Include outputs for exceptions e.g. price: €4, paid amount: €3. Any ideas on how to solve this Please?
This is where i have gotten to so far:
function checkCashRegister(price, cash, cid) {
var change = cash * 100 - price * 100; // (In cents)
var yourCash = {};
var myCash = {};
var i = 0;
const BILLS = [
["FIFTY", 50000],
["TWENTY", 2000],
["TEN", 1000],
["FIVE", 500],
["ONE", 100],
["QUARTER", 25],
["DIME", 10],
["NICKEL", 5],
["PENNY", 1]
// No change? Done.
if (change === 0) {
return {
status: "CLOSED",
change: cid
};
}
// Swap out array for an object
cid.forEach(money => {
myCash[money[0]] = parseInt(money[1] * 100);
});
// Give bills big -> small until change = 0 or fail
while(i < BILLS.length && change > 0) {
var billName = BILLS[i][0];
var billValue = BILLS[i][1];
// Can accept && give change
if (change - billValue > 0 && myCash[billName] > 0) {
// Set yourCash[billName]
yourCash[billName] = 0;
// Give as many of this bill as I can.
while(change - billValue >= 0 && myCash[billName] > 0) {
yourCash[billName] += billValue / 100;
myCash[billName] = parseInt(myCash[billName] - billValue);
change -= billValue;
}
}
i++;
}
if (change === 0) {
let hasMoney = false;
Object.keys(myCash).forEach(key => {
if (myCash[key] > 0) {
hasMoney = true;
}
});
if (hasMoney) {
return {
status: "OPEN",
change: Object.keys(yourCash).map(key => {
let obj = [key, yourCash[key]];
console.log(JSON.stringify(obj));
return obj;
})};
} else {
console.log("NO Money Left...");
return {
status: "CLOSED",
change: cid
};
}
}
return {
status: "INSUFFICIENT_FUNDS",
change: []
}
}
checkcashRegister