Created
May 19, 2016 02:59
-
-
Save jmwind/2d904beb6eeff7962c35a454f24cbf84 to your computer and use it in GitHub Desktop.
Elevator Saga Take One
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
init: function(elevators, floors) { | |
var waiting_up = new Array(floors.length).fill(0); | |
var waiting_down = new Array(floors.length).fill(0); | |
function bestFloor(waiting) { | |
var max_num_waiting = 0; | |
var next_floor = 0; | |
for(var floor = 0; floor < waiting.length; floor++) { | |
var num_waiting = waiting[floor]; | |
if(num_waiting > 0 && num_waiting > max_num_waiting) { | |
next_floor = floor; | |
max_num_waiting = num_waiting; | |
} | |
} | |
return [max_num_waiting, next_floor]; | |
} | |
function nextFloor(current) { | |
var best_up = bestFloor(waiting_up); | |
var best_down = bestFloor(waiting_down); | |
console.log("best down = " + best_down + " best up = " + best_up); | |
if(best_down[0] > best_up[0]) { | |
var floor = best_down[1]; | |
waiting_down[floor] = 0; | |
return floor; | |
} else { | |
var floor = best_up[1]; | |
waiting_up[floor] = 0; | |
return floor; | |
} | |
} | |
elevators.forEach(function(elevator) { | |
elevator.on("idle", function() { | |
var destinations = elevator.getPressedFloors() | |
if(destinations.length > 0) { | |
destinations.forEach(function(d) { | |
elevator.goToFloor(d); | |
}); | |
} else { | |
elevator.goToFloor(nextFloor(elevator.currentFloor())); | |
} | |
}); | |
}); | |
floors.forEach(function(floor) { | |
floor.on("up_button_pressed", function(f) { | |
var n = f.floorNum(); | |
waiting_up[n] += 1; | |
console.log("up queue:" + waiting_up); | |
}); | |
floor.on("down_button_pressed", function(f) { | |
var n = f.floorNum(); | |
waiting_down[n] += 1; | |
console.log("down queue:" + waiting_down); | |
}); | |
}); | |
}, | |
update: function(dt, elevators, floors) { | |
// We normally don't need to do anything here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment