Elevator Door Controller Simulation
Simulate an elevator door controller using a finite state machine. The elevator door can be in one of four states: 'CLOSED', 'OPENING', 'OPEN', or 'CLOSING'.
The system processes a sequence of events. Each event is one of three strings: 'BUTTON', 'TIMER', or 'OBSTACLE'.
The state transition rules are defined as follows:
- From 'CLOSED':
- 'BUTTON' transitions to 'OPENING'.
- 'TIMER' or 'OBSTACLE' keeps the state in 'CLOSED'.
- From 'OPENING':
- 'TIMER' transitions to 'OPEN'.
- 'BUTTON' or 'OBSTACLE' keeps the state in 'OPENING'.
- From 'OPEN':
- 'TIMER' transitions to 'CLOSING'.
- 'BUTTON' or 'OBSTACLE' keeps the state in 'OPEN'.
- From 'CLOSING':
- 'BUTTON' or 'OBSTACLE' transitions to 'OPENING'.
- 'TIMER' transitions to 'CLOSED'.
Given the initial state initialState and a array of events events, return the final state of the elevator door after processing all events in order.
[ "CLOSED", "[\"BUTTON\", \"TIMER\", \"TIMER\"]" ]
Explanation. CLOSED + BUTTON -> OPENING; OPENING + TIMER -> OPEN; OPEN + TIMER -> CLOSING.
[ "CLOSING", "[\"OBSTACLE\", \"TIMER\"]" ]
Explanation. CLOSING + OBSTACLE -> OPENING; OPENING + TIMER -> OPEN.
[ "OPEN", "[\"BUTTON\", \"OBSTACLE\"]" ]
Explanation. From OPEN, BUTTON and OBSTACLE leave the door state in OPEN.
[ "CLOSED", "[]" ]
Explanation. With no events, the state remains unchanged.
[ "CLOSING", "[\"TIMER\", \"BUTTON\", \"TIMER\", \"TIMER\"]" ]
Explanation. CLOSING + TIMER -> CLOSED; CLOSED + BUTTON -> OPENING; OPENING + TIMER -> OPEN; OPEN + TIMER -> CLOSING.
[ "OPENING", "[\"TIMER\", \"TIMER\", \"TIMER\"]" ]
Explanation. OPENING + TIMER -> OPEN; OPEN + TIMER -> CLOSING; CLOSING + TIMER -> CLOSED.
Follow-up: How would you extend the state machine if each transition also logged timestamps and emitted state duration metrics?
`initialState` is one of 'CLOSED', 'OPENING', 'OPEN', or 'CLOSING'. `events` is an array of strings containing between 0 and 1000 elements. Each string in `events` is one of 'BUTTON', 'TIMER', or 'OBSTACLE'.
- Views
- 11