优先队列:模拟医院急诊科的候诊室

高优先级的患者先于低优先级的患者就医, 同样优先级的患者按照先来先服务的顺序就医。
规定:优先码的值最小的元素优先级最高。

    function Patient(name, code) {
        this.name = name;
        this.code = code;
    }
    function Queue() {
        //用队列模拟基数排序对应的Queue构造函数中的方法一个都不能少,否则会出错
        this.dataStore = [];
        this.enqueue = enqueue;
        this.dequeue = dequeue;
        this.toString = toString;
    }
    function enqueue(element) {//向队尾添加一个元素
        this.dataStore.push(element);
    }
    function dequeue() {//对dequeue()方法的重写
        var priority = 0;
        var code1 = this.dataStore[0].code;
        for ( var i = 1; i < this.dataStore.length; ++i) {
            if (this.dataStore[i].code < code1) {
                code1 = this.dataStore[i].code;
                priority = i;
            }
        }
        return this.dataStore.splice(priority, 1);
    }
    function toString() {//对toString()方法的重写
        var retStr = "";
        for ( var i = 0; i < this.dataStore.length; ++i) {
            retStr += this.dataStore[i].name + " code: "
                    + this.dataStore[i].code + " <br/>";
        }
        return retStr;
    }

    var ed = new Queue();

    var p = new Patient("Smith", 5);
    ed.enqueue(p);
    p = new Patient("Jones", 4);
    ed.enqueue(p);
    p = new Patient("Fehrenbach", 6);
    ed.enqueue(p);
    p = new Patient("Brown", 1);
    ed.enqueue(p);
    p = new Patient("Ingram", 1);
    ed.enqueue(p);

    document.write(ed.toString() + "<br />");
    var seen = ed.dequeue();
    document.write("Patient being treated: " + seen[0].name + "<br />");
    document.write("Patients waiting to be seen: " + "<br />")
    document.write(ed.toString() + "<br />");
    // 下一轮
    var seen = ed.dequeue();
    document.write("Patient being treated: " + seen[0].name + "<br />");
    document.write("Patients waiting to be seen: " + "<br />")
    document.write(ed.toString() + "<br />");
    var seen = ed.dequeue();
    document.write("Patient being treated: " + seen[0].name + "<br />");
    document.write("Patients waiting to be seen: " + "<br />")
    document.write(ed.toString());
    /*上述程序运行结果:
    Smith code: 5 
    Jones code: 4 
    Fehrenbach code: 6 
    Brown code: 1 
    Ingram code: 1 

    Patient being treated: Brown
    Patients waiting to be seen: 
    Smith code: 5 
    Jones code: 4 
    Fehrenbach code: 6 
    Ingram code: 1 

    Patient being treated: Ingram
    Patients waiting to be seen: 
    Smith code: 5 
    Jones code: 4 
    Fehrenbach code: 6 

    Patient being treated: Jones
    Patients waiting to be seen: 
    Smith code: 5 
    Fehrenbach code: 6 */

 

转载于:https://www.cnblogs.com/feile/p/5375033.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值