HomeWork for [freecodecamp.org]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
function checkCashRegister(price, cash, cid) {
//计算要找多少钱
var change = cash - price;
//从大到小找零
var newCid = [...cid]
newCid.reverse()
//单位面值大小,最大100,从大到小排列备用
var unitArr = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100].reverse()
//计算可用的金额cidTotal
var newCidValue = [];
for (let i = 0; i < newCid.length; i++) {
newCidValue.push(newCid[i][1])
}
var cidTotal = newCidValue.reduce((a, b) => a + b)

//如果要找的钱与可用金额相等
if (change === cidTotal) {
return { status: "CLOSED", change: cid }
}
//如果要找的钱大于可用金额
if (change > cidTotal) {
return { status: "INSUFFICIENT_FUNDS", change: [] }
}
//如果要找的钱小于可用金额
if (change < cidTotal) {
//计算每种面值的货币可用数量newCidNum
let newCidNum = []
for (let i = 0; i < newCid.length; i++) {
newCidNum.push(newCid[i][1] / unitArr[i])
}

let final = []
//从面值最大开始找钱
for (let i = 0; i < newCid.length; i++) {
let n = parseInt(change / unitArr[i])
//面值大的够用,接下来拿面值小的
if (n <= newCidNum[i]) {
final.push([newCid[i][0], n * unitArr[i]])
change = change - n * unitArr[i]
change = change.toFixed(2)
}
//面值大的不够用或者刚好够用,先把面值大的拿完,再拿面值小的
else {
final.push(newCid[i])
change = change - newCid[i][1]
change = change.toFixed(2)
}
}

//把不需要拿的币值清除
let newFinal = []
//统计拿出的钱
let newTotal = []
for (let i = 0; i < final.length; i++) {
if (final[i][1] !== 0) {
newFinal.push(final[i])
newTotal.push(final[i][1])
}
}

//如果拿出的钱与要找的钱相等...
//注意这里为了简化使用的是==,因为reduce()返回的是String
if (newTotal.reduce((a, b) => a + b).toFixed(2) == cash - price) {
return { status: "OPEN", change: newFinal };
}
//如果拿出来钱与要找的钱不相等...
//这种情况是因为"找不开"
else {
return { status: "INSUFFICIENT_FUNDS", change: [] }
}
}


}


console.log(checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]));