Skip to content

1279. Traffic Light Controlled Intersection 👎

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class TrafficLight {
 public:
  void carArrived(
      // ID of the car
      int carId,
      // ID of the road the car travels on. Can be 1 (road A) or 2 (road B).
      int roadId,
      // direction of the car
      int direction,
      // Use turnGreen() to turn light to green on current road.
      function<void()> turnGreen,
      // Use crossCar() to make car cross the intersection.
      function<void()> crossCar

  ) {
    std::lock_guard<std::mutex> lock(mutex);
    if (canPassRoadId != roadId) {
      canPassRoadId = roadId;
      turnGreen();
    }
    crossCar();
  }

 private:
  int canPassRoadId = 1;  // 1 := road A, 2 := road B
  std::mutex mutex;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class TrafficLight {
  public void carArrived(
      // ID of the car
      int carId,
      // ID of the road the car travels on. Can be 1 (road A) or 2 (road B).
      int roadId,
      // direction of the car
      int direction,
      // Use turnGreen() to turn light to green on current road.
      Runnable turnGreen,
      // Use crossCar() to make car cross the intersection.
      Runnable crossCar) {
    synchronized (this) {
      if (canPassRoadId != roadId) {
        canPassRoadId = roadId;
        turnGreen.run();
      }
      crossCar.run();
    }
  }

  private int canPassRoadId = 1; // 1 := road A, 2 := road B
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class TrafficLight:
  def __init__(self):
    self.canPassRoadId = 1  # 1 := road A, 2 := road B

  def carArrived(
      self,
      # ID of the car
      carId: int,
      # ID of the road the car travels on. Can be 1 (road A) or 2 (road B).
      roadId: int,
      # direction of the car
      direction: int,
      # Use turnGreen() to turn light to green on current road.
      turnGreen: Callable[[], None],
      # Use crossCar() to make car cross the intersection.
      crossCar: Callable[[], None]
  ) -> None:
    if roadId != self.canPassRoadId:
      self.canPassRoadId = roadId
      turnGreen()
    crossCar()