Skip to content

Instantly share code, notes, and snippets.

@yock
Last active April 13, 2016 19:50
Show Gist options
  • Save yock/7f55144fb1f67f5ea7943d16edcffe81 to your computer and use it in GitHub Desktop.
Save yock/7f55144fb1f67f5ea7943d16edcffe81 to your computer and use it in GitHub Desktop.
elevator_saga.js

Elevator Saga

A programming challenge for dispatching elevators. If you've ever waited for an elevator and thought about how much sorter the wait would be if you were the programmer, give this a try.

http://play.elevatorsaga.com/

About the Algorithm

This very simplistic implementation attempts to do just two things:

  1. Always choose the elevator car with the fewest queued destinations.
  2. Never push a destination onto the queue if it's already there.

When ran against their examples it's clear that the first elevator is constantly working hard while the remaining elevators sit mostly idle. A naive round-robin approach might work better than attempting to identify nearly-idle elevators.

About the Implementation

{
init: function(elevators, floors) {
_.each(elevators,function(elevator) {
elevator.on('floor_button_pressed',function(floorNum){
if(!elevator.destinationQueue.includes(floorNum)) {
elevator.goToFloor(floorNum);
}
});
});
_.each(floors, function(floor) {
floor.on('up_button_pressed down_button_pressed', function() {
var assigned = _.sortBy(elevators, function(elevator) {
elevator.destinationQueue.length;
})[0];
var floorNum = floor.floorNum();
if(!assigned.destinationQueue.includes(floorNum)) {
assigned.goToFloor(floorNum);
}
});
});
},
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