Skip to content

Instantly share code, notes, and snippets.

@goonoo
Created January 24, 2015 10:17
Show Gist options
  • Save goonoo/f5b0c3b2bf706a6f7c3c to your computer and use it in GitHub Desktop.
Save goonoo/f5b0c3b2bf706a6f7c3c to your computer and use it in GitHub Desktop.
My Elevator Saga solution
{
init: function(elevators, floors) {
var MAX_LOAD = 4, elevatorSize = elevators.length;
var fetchElevator = function (floor, callback) {
var candidateIdx = -1, candidateDiff = elevatorSize + 1, candidateLoadFactor = .4;
var currf, fdiff;
for (var i = 0; i < elevatorSize; i++) {
currf = elevators[i].currentFloor();
fdiff = Math.abs(currf - floor.floorNum());
if (elevators[i].destinationQueue.length === 0 &&
elevators[i].loadFactor() <= candidateLoadFactor &&
fdiff < candidateDiff) {
candidateIdx = i;
candidateDiff = fdiff;
candidateLoadFactor = elevators[i].loadFactor();
}
}
if (candidateIdx === -1) {
setTimeout(function () {
fetchElevator(floor, callback);
}, 10);
return;
}
return callback(elevators[candidateIdx]);
};
var sortQueue = function (floorNum, elevator) {
var newQueue = [], oldQueue = elevator.destinationQueue, l = oldQueue.length;
outerLoop:
for (var i = 0; i < l; i++) {
if (newQueue.length === 0) {
newQueue.push(oldQueue[i]);
continue;
}
for (var j = 0; j < newQueue.length; j++) {
if (Math.abs(floorNum - oldQueue[i]) < Math.abs(floorNum - newQueue[j])) {
newQueue.splice(j, 0, oldQueue[i]);
continue outerLoop;
}
}
newQueue.push(oldQueue[i]);
}
return newQueue;
};
_.each(floors, function (floor) {
var num = floor.floorNum();
floor.on("up_button_pressed down_button_pressed", function () {
fetchElevator(floor, function (elevator) {
elevator.goToFloor(num);
})
});
});
_.each(elevators, function (elevator) {
elevator.on("floor_button_pressed", function onFloorButtonPressed(floorNum) {
if (this.destinationQueue.indexOf(floorNum) > -1) {
return
} else {
this.goToFloor(floorNum);
this.destinationQueue = sortQueue(this.currentFloor(), this);
this.checkDestinationQueue();
}
}).on("stopped_at_floor", function () {
if (this.destinationQueue.length > 1) {
this.destinationQueue = sortQueue(this.currentFloor(), this);
this.checkDestinationQueue();
if (this.destinationQueue.length > 2) {
if (this.destinationQueue[0] > this.destinationQueue[1]) {
this.goingUpIndicator(false);
this.goingDownIndicator(true);
} else if (this.destinationQueue[0] < this.destinationQueue[1]) {
this.goingUpIndicator(true);
this.goingDownIndicator(false);
}
}
} else {
this.goingUpIndicator(true);
this.goingDownIndicator(true);
}
}).on("idle", function () {
this.goToFloor(parseInt(Math.random() * 8));
});
});
// init
for (var i = 1; i < elevators.length; i++) {
elevators[i].goToFloor(i*2);
}
},
update: function(dt, elevators, floors) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment