Last active
August 29, 2015 14:14
-
-
Save jauco/57b9f599de1494c968dc to your computer and use it in GitHub Desktop.
Elevator saga
This file contains 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
//level 9 | |
//level 9 | |
{ | |
init: function(elevators, floors) { | |
function reorderDestinationqueue(q) { | |
var qnew = []; | |
var alreadyInQueue = {}; | |
for (var i=0; i < q.length ; i++) { | |
if (!alreadyInQueue[q[i]]) { | |
qnew.push(q[i]); | |
} | |
alreadyInQueue[q[i]] = true; | |
} | |
return qnew; | |
} | |
function skipUselessDestinations(loadFactor, tasks, q) { | |
if (loadFactor === 1) { | |
return q.filter(function (floor) { return tasks[floor]; }); | |
} else { | |
return q; | |
} | |
} | |
elevators.forEach(scheduleElv); | |
var idleElevators = []; | |
debugger; | |
function scheduleElv(elevator, idx){ | |
elevator.idx = idx; | |
elevator.move = function weMove(floorNum) { | |
var idlePos = idleElevators.indexOf(elevator); | |
if (idlePos > -1) { | |
idleElevators.splice(idlePos, 1); | |
} | |
elevator.destinationQueue.push(floorNum); | |
elevator.destinationQueue = skipUselessDestinations(elevator.loadFactor(), elevator.tasks, reorderDestinationqueue(elevator.destinationQueue)); | |
elevator.checkDestinationQueue(); | |
return elevator.destinationQueue.indexOf(floorNum) != -1; | |
}; | |
elevator.tasks = {}; | |
elevator.on("idle", function() { | |
idleElevators.push(elevator); | |
console.log("idle", idleElevators); | |
}); | |
elevator.on("stopped_at_floor", function(floorNum) { | |
delete elevator.tasks[floorNum]; | |
}); | |
elevator.on("floor_button_pressed", function(floorNum) { | |
elevator.tasks[floorNum] = true; | |
elevator.move(floorNum); | |
}); | |
} | |
floors.forEach(function (floor) { | |
floor.on("up_button_pressed", function() { | |
if (idleElevators.length > 0) { | |
idleElevators[0].move(floor.floorNum()); | |
} else { | |
var i = 0; | |
while (elevators[i] && !elevators[i].move(floor.floorNum())) { | |
i++; | |
} | |
} | |
}) | |
floor.on("down_button_pressed", function() { | |
if (idleElevators.length > 0) { | |
idleElevators[0].move(floor.floorNum()); | |
} else { | |
var i = 0; | |
while (elevators[i] && !elevators[i].move(floor.floorNum())) { | |
i++; | |
} | |
} | |
}) | |
}); | |
}, | |
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