background image

电梯算法

某天坐电梯时被妹纸问电梯算法,于是便简单写了⼀个。

大体思路:电梯信号分为外部信号和内部信号,区别为:外部信号有方向信息,内部信号没有,
所以会对所有信号做⼀个收集。收集完成并处理后,就进行分类,分类思路:可以制定往上楼层
数和往下楼层数二个目标队列,往上的⼀个,往下的⼀个,然后定时从该二个队列中取楼层数,
其中还会有方向的判断,具体代码如下:

    

var

 upDests=[],

        downDests=[],
        index=0,
        direction=0,
        current=1,
        top=20,
        bottom=-4,
        insideSignals=[],
        outsideSignals=[];
    
    

function

 addDest(sg){

        

if

 (

typeof

 sg === "object") {

            

if

(sg.d===1 && indexOf(upDests,sg.n)===-1){

                upDests.push(sg.n);
                upDests.sort(

function

(a,b){

return

 a>b});

            }
            
            

if

(sg.d===-1 && indexOf(downDests,sg.n)===-1){

                downDests.push(sg.n);
                downDests.sort(

function

(a,b){

return

 a<b});

            }
        
        
        }

else

 

if

 (!isNaN(sg)) {

            

if

(sg>current){

                

if

(indexOf(upDests,sg)===-1){

                    upDests.push(sg);
                    upDests.sort(

function

(a,b){

return

 a>b});

                }
            }

else

 

if

(sg<current){

                

if

(indexOf(downDests,sg)===-1){

                    downDests.push(sg);
                    downDests.sort(

function

(a,b){

return

 a<b});

                }
            }
        }
        
        

if

(upDests.length===1 && downDests.length === 0 && direction === 0){

            direction=1;
        }
        
        

if

(upDests.length===0 && downDests.length === 1 && direction === 0){

            direction=-1;