Skip to content

Instantly share code, notes, and snippets.

@AryanJ-NYC
Last active August 24, 2016 14:56
Show Gist options
  • Save AryanJ-NYC/ea15def0698d284e088ad1c79abfc09d to your computer and use it in GitHub Desktop.
Save AryanJ-NYC/ea15def0698d284e088ad1c79abfc09d to your computer and use it in GitHub Desktop.
My algorithm to Elevator Saga: http://play.elevatorsaga.com/
{
init: function(elevators, floors) {
function isFloorQueued (floorNum, elevator) {
if (elevator) {
let destinationQ = elevator.destinationQueue;
for (let destIndex = 0; destIndex < destinationQ.length; ++destIndex) {
if (destinationQ[destIndex] == floorNum){
return true;
}
}
}
return false;
}
for (let elevIndex = 0; elevIndex < elevators.length; ++elevIndex) {
let elevator = elevators[elevIndex];
elevator.on("idle", function() {
this.goToFloor(0);
});
elevator.on("floor_button_pressed", function (floorNum) {
if (!isFloorQueued(floorNum, this)) {
this.goToFloor(floorNum);
}
if (this.currentFloor() == 0) {
this.destinationQueue.sort();
}
else if (this.currentFloor() == floors.length-1) {
this.destinationQueue.sort(function(a, b){return b-a});
}
});
elevator.on("stopped_at_floor", function (floorNum) {
});
elevator.on("passing_floor", function (floorNum) { // if passing a queued floor and full, just stop
if (this.loadFactor() == 1 && isFloorQueued(floorNum, this)) this.goToFloor(floorNum, true);
})
}
for (let floorIndex = 0; floorIndex < floors.length; ++floorIndex) {
let floor = floors[floorIndex];
floor.on("up_button_pressed down_button_pressed", function() {
let isQueued = false;
for (let elevIndex = 0; elevIndex < elevators.length; ++elevIndex) {
let elevator = elevators[elevIndex];
if (isFloorQueued(floor, elevator)) isQueued = true;
}
if (! isQueued) { // if not queued, find closest non-full elevator
let eIndex = 0,
minDistance = Number.POSITIVE_INFINITY;
for (let elevIndex = 0; elevIndex < elevators.length; ++elevIndex) {
let elevator = elevators[elevIndex];
let currentDistance = Math.abs(floorIndex - elevator.currentFloor());
if (currentDistance < minDistance && elevator.loadFactor() != 1) {
minDistance = currentDistance;
eIndex = elevIndex;
}
}
if (elevators[eIndex].loadFactor() != 1)
elevators[eIndex].goToFloor(floorIndex);
}
});
}
},
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