-
Notifications
You must be signed in to change notification settings - Fork 320
aonsager's solution
Alex Onsager edited this page Jan 23, 2015
·
7 revisions
The general strategy is for each elevator to keep moving up and down, and to pick up any people along the way.
{
init: function(elevators, floors) {
var downQueue = [];
var upQueue = [];
var idleElevators = []
var topFloor = floors.length - 1;
_.each(elevators, function(elevator) {
elevator.on("idle", function() {
// record that this elevator is idle, so it can be woken up later
idleElevators.push(elevator);
});
elevator.on("floor_button_pressed", function(floorNum) {
// add the new floor to the queue if it wasn't already requested
if (elevator.destinationQueue.indexOf(floorNum) < 0 ) {
elevator.destinationQueue.push(floorNum);
// sort to make sure we visit floors in order
elevator.destinationQueue = elevator.destinationQueue.sort();
if (elevator.goingDownIndicator()) {
elevator.destinationQueue = elevator.destinationQueue.reverse();
}
// apply the changes
elevator.checkDestinationQueue();
}
});
elevator.on("stopped_at_floor", function(floorNum) {
if (floorNum == 0) {
// start moving up once we reach the bottom
elevator.goingDownIndicator(false);
elevator.goingUpIndicator(true);
} else if (floorNum == topFloor) {
// start moving down once we reach the top
elevator.goingUpIndicator(false);
elevator.goingDownIndicator(true);
}
});
elevator.on("passing_floor", function(floorNum, direction) {
// check if there is someone here who wants to go our direction
queue = direction == "up" ? upQueue : downQueue;
index = queue.indexOf(floorNum);
if ( index >= 0) {
// if yes, remove them from the queue and stop for them
queue.splice(index, 1);
elevator.goToFloor(floorNum, true);
} else {
}
});
});
_.each(floors, function(floor) {
floor.on("up_button_pressed", function() {
// if there is an idle elevator, wake it up
if (idleElevators.length > 0) {
elevator = idleElevators.shift();
elevator.goToFloor(floor.floorNum());
} else {
// otherwise add this floor to the queue and wait for an elevator to pass
if (upQueue.indexOf(floor.floorNum()) < 0) upQueue.push(floor.floorNum());
}
});
floor.on("down_button_pressed", function() {
// if there is an idle elevator, wake it up
if (idleElevators.length > 0) {
elevator = idleElevators.shift();
elevator.goToFloor(floor.floorNum());
} else {
// otherwise add it to the queue and wait for an elevator to pass
if (downQueue.indexOf(floor.floorNum()) < 0) downQueue.push(floor.floorNum());
}
});
});
},
update: function(dt, elevators, floors) {
// We normally don't need to do anything here
}
}
Play it yourself at play.elevatorsaga.com