FreeCodeCamp---advanced Algorithm Scripting解法

时间:2024-06-17 12:37:02

Exact Change

设计一个收银程序 checkCashRegister() ,其把购买价格(price)作为第一个参数 , 付款金额 (cash)作为第二个参数, 和收银机中零钱 (cid) 作为第三个参数.

cid 是一个二维数组,存着当前可用的找零.

当收银机中的钱不够找零时返回字符串 "Insufficient Funds". 如果正好则返回字符串 "Closed".

否则, 返回应找回的零钱列表,且由大到小存在二维数组中.

 function checkCashRegister(price, cash, cid) {
var arr=[]; //应找回的零钱列表
var cashPrice=[]; //一种钱代表的金额
var cashName=[]; //钱的名字
var cashItemSum=[]; //一种钱的总数
var change=Math.round((cash-price)*100)/100; //要找回的零钱
var sumCash=0;
cid.forEach(function(item,index,array){
if(item[1]>0){
cashName.push(item[0]);
cashItemSum.push(item[1]);
sumCash += item[1];
}
}); cashPrice=cashName.map(function(item,index,array){
switch (item){
case "PENNY":
return 0.01;
case "NICKEL":
return 0.05;
case "DIME":
return 0.1;
case "QUARTER":
return 0.25;
case "ONE":
return 1;
case "FIVE":
return 5;
case "TEN":
return 10;
case "TWENTY":
return 20;
case "ONE HUNDRED":
return 100;
}
}); sumCash=Math.round(sumCash*100)/100; //对sumCash保留两位小数 switch (true){
case change>sumCash:
return "Insufficient Funds";
case change === sumCash:
return "Closed";
default:
approachChange(change);
if(arr.length===0){
return "Insufficient Funds";
}else{
return arr;
}
} function approachChange(change){
var index=0;
if(change>cashPrice[cashPrice.length-1]){
index=cashPrice.length-1;
} for(var i=0; i<cashPrice.length-1; i++){
if(cashPrice[i]<=change && change<cashPrice[i+1] && cashItemSum[i]!==0){
index=i;
}
} var itemNeedSum=Math.floor(change/cashPrice[index]) * cashPrice[index];
var needMin=Math.min(itemNeedSum,cashItemSum[index]);
var x=Math.round( (change-needMin)*100 )/100; if(x>0 && index===0){
return;
} arr.push([cashName[index], needMin]); if(x===0){
return;
}else{
cashPrice=cashPrice.slice(0,index);
approachChange(x);
}
} } checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1.00], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]);