Junior — Middle
Can you explain what a finite state machine (FSM) means in the context of programming and system design?
sobes.tech AI
Answer from AI
A Finite State Machine (FSM) is a computational model that describes a system through a finite number of states and transitions between them in response to events or input data. In programming and system design, FSMs are often used to control the behavior of a program, where at each moment the system is in one of the states, and transitions occur according to certain rules.
Example: managing the states of a user interface (for example, a button can be in states "normal", "hovered", "pressed"), or processing protocols where different messages transition the system into different states.
Example in Python:
class TrafficLightFSM:
def __init__(self):
self.state = 'RED'
def on_event(self, event):
if self.state == 'RED' and event == 'timer':
self.state = 'GREEN'
elif self.state == 'GREEN' and event == 'timer':
self.state = 'YELLOW'
elif self.state == 'YELLOW' and event == 'timer':
self.state = 'RED'
traffic_light = TrafficLightFSM()
print(traffic_light.state) # RED
traffic_light.on_event('timer')
print(traffic_light.state) # GREEN