Practice/Amazon/Traffic System
Traffic System
Object Oriented DesignMust
Problem
Design an object-oriented system to manage traffic lights at a four-way intersection. Your system must coordinate multiple traffic lights to ensure safe traffic flow while preventing accidents caused by conflicting green lights.
The system should handle standard traffic light cycles where opposing directions (North-South or East-West) can have green lights simultaneously, but perpendicular directions must never both be green. Additionally, implement features for emergency vehicle priority, pedestrian crossing requests, and adaptive timing based on traffic density.
Requirements
- TrafficLight Class: Represent individual traffic lights with states (RED, YELLOW, GREEN) for each direction
- Intersection Class: Coordinate multiple traffic lights and manage state transitions
- Safety Rules: Ensure conflicting directions never have green lights simultaneously
- State Transitions: Implement proper sequencing (GREEN → YELLOW → RED, never skip yellow)
- Emergency Override: Allow emergency vehicles to get immediate priority
- Pedestrian Support: Handle pedestrian crossing requests that stop all vehicle traffic
- Adaptive Timing: Adjust green light duration based on traffic density
- Thread Safety: Design with concurrency in mind for real-world deployment
Constraints
- Minimum yellow light duration: 3 seconds
- Standard green light duration: 30-60 seconds
- The system must prevent simultaneous green lights in conflicting directions
- Emergency override must complete within 5 seconds
- Support 4 main directions: North, South, East, West
Examples
Example 1: Basic Traffic Cycle
Initial State: All lights RED Step 1: North and South lights turn GREEN (opposing directions safe) Step 2: After 30 seconds, North/South turn YELLOW Step 3: After 3 seconds, North/South turn RED Step 4: East and West lights turn GREEN Step 5: Cycle repeats
Example 2: Emergency Vehicle Priority
`
Current State: East/West lights GREEN
Emergency Vehicle: Approaches from North
Action:
- East/West immediately turn YELLOW
- After yellow period, turn RED
- North light turns GREEN for emergency vehicle
- Resume normal cycle after emergency passes
`
Example 3: Pedestrian Crossing
`
Current State: North/South lights GREEN
Pedestrian Action: Presses crossing button for East-West crosswalk
Response:
- North/South transition through YELLOW to RED
- All vehicle lights remain RED
- Pedestrian WALK signal activates
- After crossing time, resume vehicle traffic cycle
`