Skip to content

Instantly share code, notes, and snippets.

@cspags
Last active August 29, 2015 14:13
Show Gist options
  • Save cspags/93f18a2fe505bf4f1686 to your computer and use it in GitHub Desktop.
Save cspags/93f18a2fe505bf4f1686 to your computer and use it in GitHub Desktop.
Fairly simple strategy for beating challenges 1 - 5
{
init: function(elevators, floors) {
// set up an array to track which floors have people waiting
floorStatus = [];
$.each(floors, function(index, floor) {
floorStatus.push(false);
floor.on("down_button_pressed", function() {
floorStatus[floor.floorNum()] = true;
});
floor.on("up_button_pressed", function() {
floorStatus[floor.floorNum()] = true;
});
});
$.each(elevators, function(index, elevator) {
// for each elevator track which buttons have been pressed
var buttonsPressed = [];
elevator.on("idle", function() {
if(buttonsPressed.length > 0) {
// remove duplicate button presses
var unique = [];
$.each(buttonsPressed, function(i, el){
if($.inArray(el, unique) === -1)
unique.push(el);
});
buttonsPressed = unique;
// calculate closest floor to go to next
var minDist = 99999;
var minDistIndex = -1;
$.each(buttonsPressed, function(i, el) {
if(Math.abs(el - elevator.currentFloor()) < minDist) {
minDist = Math.abs(el - elevator.currentFloor());
minDistIndex = i;
}
});
elevator.goToFloor(buttonsPressed.splice(minDistIndex, 1)[0]);
} else {
// elevator is empty, so look at which floors have people waiting and go to the closest one
var minDist = 99999;
var minDistIndex = index;
$.each(floorStatus, function(i, el) {
if(el) {
if(Math.abs(i - elevator.currentFloor()) < minDist) {
minDist = Math.abs(i - elevator.currentFloor());
minDistIndex = i;
}
}
});
elevator.goToFloor(minDistIndex);
}
});
elevator.on("stopped_at_floor", function(floorNum) {
floorStatus[floorNum] = false;
});
elevator.on("floor_button_pressed", function(floorNum) {
buttonsPressed.push(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