设计一个收银程序 checkCashRegister() ,其把购买价格(price)作为第一个参数 , 付款金额 (cash)作为第二个参数, 和收银机中零钱 (cid) 作为第三个参数.
cid 是一个二维数组,存着当前可用的找零.
当收银机中的钱不够找零时返回字符串 "Insufficient Funds". 如果正好则返回字符串 "Closed".
否则, 返回应找回的零钱列表,且由大到小存在二维数组中.
题目解读: 使用cid项 能否的组合出cash - price 值,可以则返回"Closed", 小于则返回"Insufficient Funds",否则返回由大到小零钱列表的二维数组.
var drawer = {
PENNY: 0.01,
NICKEL: 0.05,
DIME: 0.10,
QUARTER: 0.25,
ONE: 1,
FIVE: 5,
TEN: 10,
TWENTY: 20,
'ONE HUNDRED': 100
};
function checkCashRegister(price, cash, cid) {
var change = cash - price;
var total = 0;
//计算零钱总额
for (var i = 0; i < cid.length; i++) {
total += cid[i][1];
}
total = Number(total.toFixed(2));
if (total < change) {
return "Insufficient Funds";
} else if (total === change) {
return "Closed";
} else {
return payBack(change, cid, total);
}
}
function payBack(change, cid, total) {
var back = [];
for (var i = cid.length - 1; i >= 0; i--) {
var type = cid[i][0];
var money = cid[i][1];
if (money === 0) continue;
if (money < change) {
back.push(cid[i]);
change -= money;
} else if (money > change) {
var drawerCash = Math.floor(change / drawer[type]) * drawer[type];
if (drawerCash === 0 && total - money < change) {
return "Insufficient Funds";
} else if (drawerCash === 0) {
continue;
} else {
var drawerBack = [];
drawerBack.push(type);
drawerBack.push(drawerCash);
back.push(drawerBack);
change -= drawerCash;
}
}
change = Number(change.toFixed(2));
}
if (change === 0) {
return back;
} else {
return "Insufficient Funds";
}
}