Exact Change
设计一个收银程序 checkCashRegister()
,其把购买价格(price
)作为第一个参数 , 付款金额 (cash
)作为第二个参数, 和收银机中零钱 (cid
) 作为第三个参数.
cid
是一个二维数组,存着当前可用的找零.
当收银机中的钱不够找零时返回字符串 "Insufficient Funds"
. 如果正好则返回字符串 "Closed"
.
否则, 返回应找回的零钱列表,且由大到小存在二维数组中.
1 function checkCashRegister(price, cash, cid) { 2 var arr=[]; //应找回的零钱列表 3 var cashPrice=[]; //一种钱代表的金额 4 var cashName=[]; //钱的名字 5 var cashItemSum=[]; //一种钱的总数 6 var change=Math.round((cash-price)*100)/100; //要找回的零钱 7 var sumCash=0; 8 cid.forEach(function(item,index,array){ 9 if(item[1]>0){ 10 cashName.push(item[0]); 11 cashItemSum.push(item[1]); 12 sumCash += item[1]; 13 } 14 }); 15 16 cashPrice=cashName.map(function(item,index,array){ 17 switch (item){ 18 case "PENNY": 19 return 0.01; 20 case "NICKEL": 21 return 0.05; 22 case "DIME": 23 return 0.1; 24 case "QUARTER": 25 return 0.25; 26 case "ONE": 27 return 1; 28 case "FIVE": 29 return 5; 30 case "TEN": 31 return 10; 32 case "TWENTY": 33 return 20; 34 case "ONE HUNDRED": 35 return 100; 36 } 37 }); 38 39 40 sumCash=Math.round(sumCash*100)/100; //对sumCash保留两位小数 41 42 switch (true){ 43 case change>sumCash: 44 return "Insufficient Funds"; 45 case change === sumCash: 46 return "Closed"; 47 default: 48 approachChange(change); 49 if(arr.length===0){ 50 return "Insufficient Funds"; 51 }else{ 52 return arr; 53 } 54 } 55 56 57 58 function approachChange(change){ 59 var index=0; 60 if(change>cashPrice[cashPrice.length-1]){ 61 index=cashPrice.length-1; 62 } 63 64 for(var i=0; i<cashPrice.length-1; i++){ 65 if(cashPrice[i]<=change && change<cashPrice[i+1] && cashItemSum[i]!==0){ 66 index=i; 67 } 68 } 69 70 var itemNeedSum=Math.floor(change/cashPrice[index]) * cashPrice[index]; 71 var needMin=Math.min(itemNeedSum,cashItemSum[index]); 72 var x=Math.round( (change-needMin)*100 )/100; 73 74 if(x>0 && index===0){ 75 return; 76 } 77 78 arr.push([cashName[index], needMin]); 79 80 81 if(x===0){ 82 return; 83 }else{ 84 cashPrice=cashPrice.slice(0,index); 85 approachChange(x); 86 } 87 } 88 89 } 90 91 92 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]]);
时间: 2024-10-11 11:38:56