📅  最后修改于: 2023-12-03 14:58:19.913000             🧑  作者: Mango
This problem from the GATE CS 2013 exam asks the candidate to write a program in C++ to simulate the working of a two-way traffic intersection equipped with traffic lights.
The program should simulate the following operations:
The solution to this problem is a straightforward implementation of the rules outlined in the problem statement:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
const int CYCLE_TIME = 10; // in seconds
enum TrafficLightState {
GREEN,
YELLOW,
RED
};
class TrafficLight {
public:
TrafficLight() {
state = GREEN;
startTime = chrono::system_clock::now();
}
void setState(TrafficLightState newState) {
state = newState;
startTime = chrono::system_clock::now();
}
TrafficLightState getState() const {
return state;
}
bool isGreen() const {
return state == GREEN;
}
bool isRed() const {
return state == RED;
}
bool isYellow() const {
return state == YELLOW;
}
void tick() {
auto elapsed = chrono::system_clock::now() - startTime;
if (elapsed > chrono::seconds(CYCLE_TIME)) {
if (state == GREEN) {
state = YELLOW;
} else if (state == YELLOW) {
state = RED;
} else {
state = GREEN;
}
startTime = chrono::system_clock::now();
}
}
private:
TrafficLightState state;
chrono::system_clock::time_point startTime;
};
int main() {
TrafficLight northSouth;
TrafficLight eastWest;
while (true) {
cout << "North-South traffic ";
if (northSouth.isGreen()) {
cout << "can pass." << endl;
} else {
cout << "must stop." << endl;
}
cout << "East-West traffic ";
if (eastWest.isGreen()) {
cout << "can pass." << endl;
} else {
cout << "must stop." << endl;
}
northSouth.tick();
eastWest.tick();
this_thread::sleep_for(chrono::seconds(1));
}
return 0;
}
The code above creates a TrafficLight
class to model each traffic light. The TrafficLight
class has a state (either GREEN
, YELLOW
, or RED
), a start time (when the state was last changed), and methods for changing the state and updating the state based on the elapsed time.
The main loop of the program alternates between checking the northSouth
and eastWest
traffic lights and printing a message indicating whether traffic is permitted to pass. The loop calls the tick()
method of each TrafficLight
, which updates the state if the elapsed time exceeds the configured cycle time.
The program also sleeps for one second at the end of each iteration of the loop to simulate the passage of time.
This solution provides a basic implementation of a two-way traffic intersection with traffic lights. The program can be customized by adjusting the CYCLE_TIME
constant to change the length of each light cycle.