[FCC] Cash Register 计算找零

题目地址:
https://chinese.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register

关键在于如何找零,从大面额开始尝试,如果最后 change 变为 0 找零成功。如果不转换为美分再计算要注意浮点数的误差。

function checkCashRegister(price, cash, cid) {
  const table = {
    "PENNY": 0.01,
    "NICKEL": 0.05,
    "DIME": 0.1,
    "QUARTER": 0.25,
    "ONE": 1,
    "FIVE": 5,
    "TEN": 10,
    "TWENTY": 20,
    "ONE HUNDRED": 100
  };
  // console.log(cid)
  let change = cash - price;
  // console.log(change)
  let status = "OPEN";
  // 寻找找零方案
  let res = [];
  for (let i = cid.length-1; i >= 0; i--) {
    let coin = [cid[i][0], 0];
    while (change >= table[coin[0]] && coin[1] < cid[i][1]) {
      change -= table[coin[0]];
      change = Math.round(change*100) /100;  // 精确到小数点后2位
      coin[1] += table[coin[0]];
      coin[1] = Math.round(coin[1] * 100) /100;
    }
    console.log(coin, change)
    if (coin[1] > 0) {
      res.push(coin);
    }
  }

  // console.log(res)
  if (change == 0) {
    let isClosed = false;
    if (res.reduce((total, value) => total + value[1], 0) == cid.reduce((total, it) => total+it[1], 0)) {
      isClosed = true;
    }
    if (isClosed) {
      status = "CLOSED";
      res = cid;
    }
  } else {
    status = "INSUFFICIENT_FUNDS"
    res.length = 0
  }
  return {status: status, change: res};
}
posted @ 2022-06-23 12:34  wngtk  阅读(35)  评论(0编辑  收藏  举报