Last active
November 15, 2019 15:57
-
-
Save oguzcanhuner/6e333defaeed3453be49c0c40f418e5e to your computer and use it in GitHub Desktop.
Elevator solution by Oz, Tim and Adam
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
init: function(elevators, floors) { | |
var self = this; | |
var awaitingFloors = {} | |
floors.forEach(function(floor){ | |
floor.on("up_button_pressed", function() { | |
awaitingFloors[floor.floorNum()] = 1; | |
}) | |
floor.on("down_button_pressed", function() { | |
awaitingFloors[floor.floorNum()] = 1; | |
}) | |
}) | |
elevators.forEach(function(elevator){ | |
elevator.on("idle", function() { | |
targets = elevator.getPressedFloors() | |
nearestRequestedFloor = self.findNearestFloor(elevator.currentFloor(), targets) | |
nearestWaitingFloor = self.findNearestFloor(elevator.currentFloor(), Object.keys(awaitingFloors)) | |
if(nearestRequestedFloor && elevator.loadFactor() >= 0.5){ | |
floor = nearestRequestedFloor | |
}else{ | |
floor = self.findNearestFloor(elevator.currentFloor(), [nearestRequestedFloor, nearestWaitingFloor]) | |
} | |
if(floor){ | |
elevator.goToFloor(floor); | |
delete awaitingFloors[floor] | |
}else{ | |
elevator.goToFloor(0); | |
} | |
}); | |
}) | |
}, | |
update: function(dt, elevators, floors) { | |
// We normally don't need to do anything here | |
}, | |
findNearestFloor: function(currentFloor, floors) { | |
currentDistance = null | |
result = null | |
floors.forEach(function(floor){ | |
if(!floor){ | |
return | |
} | |
distance = Math.abs(currentFloor - floor) | |
if(!currentDistance || currentDistance > distance){ | |
currentDistance = distance | |
result = floor | |
} | |
}) | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment