There is an intersection of two roads. Road A allows cars to travel from North to South in direction 1 and from South to North in direction 2. Road B allows cars to travel from West to East in direction 3 and from East to West in direction 4.
There is a traffic light located on each road before the intersection. A traffic light can either be green or red:
- Green means cars can cross the intersection in both directions of the road
- Red means cars in both directions cannot cross the intersection and must wait
The traffic lights cannot be green on both roads at the same time. Initially, the traffic light is green on road A and red on road B.
Design a deadlock-free traffic light controlled system. Implement the function carArrived(carId, roadId, direction, turnGreen, crossCar) where:
carIdis the id of the car that arrivedroadIdis the id of the road (1 for road A, 2 for road B)directionis the direction of the carturnGreenis a function to turn the traffic light green on the current roadcrossCaris a function to let the current car cross the intersection
Constraints: Your solution must avoid deadlock and ensure only cars from the same road cross simultaneously.
Input & Output
Constraints
- 1 ≤ carId ≤ 1000
- roadId ∈ {1, 2} (1 for road A, 2 for road B)
- direction ∈ {1, 2, 3, 4}
- Initially road A is green, road B is red
- Only one road can be green at any time