题解 | #自动售货系统#

自动售货系统

https://www.nowcoder.com/practice/cd82dc8a4727404ca5d32fcb487c50bf

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

/**
 * 自动售货机中商品为6种商品
 * 商品数由 [初始化命令] 设置
 */
var items = {
    "A1":{price: 2, amount: 0},
    "A2":{price: 3, amount: 0},
    "A3":{price: 4, amount: 0},
    "A4":{price: 5, amount: 0},
    "A5":{price: 8, amount: 0},
    "A6":{price: 6, amount: 0}
}

/**
 * 存钱盒内放置1元、2元、5元、10元钱币
 * [初始化命令] 设置各种面额钱币张数
 */
var moneyBox = new Map();
moneyBox.set(10, 0);
moneyBox.set(5, 0);
moneyBox.set(2, 0);
moneyBox.set(1, 0);

var balance = 0;
/**
 * 投币、购买商品、退币、查询库存商品及存钱盒信息
 */
void async function () {
    // Write your code here
    while(line = await readline()){
        // 命令字与第一个参数间使用一个空格分隔,多条命令采用分号隔开
        let cmds = line.trim().split(';');
        // let cmds = ["aada"]
        for(let cmd of cmds){
            if(cmd === "") continue;
            let split = cmd.indexOf(' ');
            let op = ""
            let data = ""
            if(split === -1){
                op = cmd;
                data = undefined
            }
            else{
                op = cmd.substring(0, split);
                data = cmd.substring(split + 1);
            }
            console.log(runCommand(op, data));
            // console.log(`${op}|${data}`)
        }
    }
}()

function runCommand(op, data){
    switch(op){
        case "r": return init(data);
        case "p": return pay(data);
        case "b": return buy(data);
        case "c": return cancel();
        case "q": return query(data);
        default: return "E010:Parameter error";
    }
}

// r 22-18-21-21-7-20 3-23-10-6;
function init(data){
    let temp = data.split(' ');
    let itemAmounts = temp[0].split('-');
    let moneyAmounts = temp[1].split('-');
    itemAmounts.forEach((val, i)=>{itemAmounts[i] = parseInt(val)});
    moneyAmounts.forEach((val, i)=>{moneyAmounts[i] = parseInt(val)});

    // 物品数量
    for(let i = 1; i <= 6; i++){
        items[`A${i}`].amount = itemAmounts[i-1];
    }
    // 钱币数量
    moneyBox.set(1, moneyAmounts[0]);
    moneyBox.set(2, moneyAmounts[1]);
    moneyBox.set(5, moneyAmounts[2]);
    moneyBox.set(10, moneyAmounts[3]);

    return "S001:Initialization is successful";
}

// 2.2 投币 | p 1;
function pay(data){
    let amount = parseInt(data);

    // 投入非1元、2元、5元、10元的钱币面额(钱币面额不考虑负数、字符等非正整数的情况)
    if(amount !== 1 && amount !== 2 && amount !== 5 && amount !== 10){
        return "E002:Denomination error";
    }

    /**
     * 1元和2元面额钱币总额小于本次投入的钱币面额
     *  投入1元和2元面额钱币不受此限制
     */
    if((amount === 5 || amount === 10) && moneyBox.get(1) + moneyBox.get(2)*2 < amount){
        return "E003:Change is not enough, pay fail";
    }

    // 商品全部销售完毕,投币失败
    let empty = true;
    for(let item in items){
        if(items[item].amount !== 0){
            empty = false;
            break;
        }
    }
    if(empty) return "E005:All the goods sold out";
    
    // 投币成功
    balance += amount;
    moneyBox.set(amount, moneyBox.get(amount) + 1);
    return `S002:Pay success,balance=${balance}`;
}

// 2.3 购买商品 b A1
function buy(data){
    // 购买的商品不在商品列表中
    let itemInfo = items[data];
    if(itemInfo === undefined){
        return "E006:Goods does not exist";
    }
    // 购买的商品的数量为0
    if(itemInfo.amount === 0){
        return "E007:The goods sold out";
    }
    // 投币余额小于待购买商品价格
    if(itemInfo.price > balance){
        return "E008:Lack of balance";
    }
    /**
     * 购买成功
     * 购买商品成功后,自动售货机中对应商品数量减1,投币余额扣除本次购买商品的价格。
     */
    items[data].amount--;
    balance -= itemInfo.price;
    return `S003:Buy success,balance=${balance}`;
}

function cancel(){
    // 投币余额等于0
    if(balance === 0) return "E009:Work failure";
    // 投币余额大于0
    // 按钱币总张数最少的原则进行退币
    let ps = [10, 5, 2, 1];
    let res = [];
    for(let p of ps){
        let count = 0;
        while(moneyBox.get(p) > 0 && balance >= p){
            count++;
            balance-=p;
            moneyBox.set(p, moneyBox.get(p) - 1);
        }
        res.push(`${p} yuan coin number=${count}`);
    }
    return res.reverse().join('\n');
}

function query(data){
    let res = [];
    if(data === '0'){
        for(let i = 1; i <= 6; i++){
            let name = `A${i}`
            res.push(`${name} ${items[name].price} ${items[name].amount}`)
        }
    }
    else if(data === "1"){
        res.push(`1 yuan coin number=${moneyBox.get(1)}`);
        res.push(`2 yuan coin number=${moneyBox.get(2)}`);
        res.push(`5 yuan coin number=${moneyBox.get(5)}`);
        res.push(`10 yuan coin number=${moneyBox.get(10)}`);
    }
    else{
        return "E010:Parameter error";
    }
    return res.join('\n');
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:52
点赞 评论 收藏
分享
牛客717484937号:双飞硕没实习挺要命的
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务