FunctionRacerProblemsRace

Elevator That Sweeps Up and Down

MediumClassesPython, JavaScript, TypeScript, Java, C++

Implement a class Elevator for one elevator serving floors 0 to top. It starts at floor 0, standing still. Write these methods:

- Elevator(top) makes the elevator.
- request(floor) asks the elevator to stop at floor. Returns false if the elevator is at floor right now or floor is already requested (then nothing changes); otherwise it saves the request and returns true.
- tick() lets one step of time pass and returns the floor of the elevator afterwards. With no requests, nothing happens. Otherwise:
1. A standing elevator heads toward the nearest requested floor, going up when two are equally near. A moving elevator with no requested floor ahead of it in its direction turns around.
2. It moves one floor. If it arrives at a requested floor, that request is done, and if no requests are left it stands still.
- get_heading() returns "up", "down" or "idle" (standing still).
- list_pending() returns the requested floors in increasing order.

The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.

Example 1

Elevator(9)
request(5) returns true
request(2) returns true
tick() returns 1
tick() returns 2
request(1) returns true
tick() returns 3
tick() returns 4
tick() returns 5
list_pending() returns [1]
tick() returns 4
get_heading() returns "down"

Floor 2 is nearer, so the elevator starts upward and stops there. It keeps going up to 5 even though floor 1 was requested behind it, and only then turns around.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Classes problems