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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
#include <iostream> #include <vector> #include <cstdlib> #include <ctime> #include <thread> #include <chrono> // Constants const int ROAD_LENGTH = 20; // Length of the road segment const int INITIAL_CARS = 5; // Initial number of cars on the road const int CAR_SPEED = 1; // Speed at which cars move (in units per time step) const int SIMULATION_STEPS = 50; // Number of simulation steps // Function to initialize the road with cars void initializeRoad(std::vector<int>& road) { for (int i = 0; i < INITIAL_CARS; ++i) { road[i] = 1; // Place cars on the road } } // Function to print the road state void printRoad(const std::vector<int>& road) { for (int pos : road) { std::cout << (pos == 1 ? 'C' : '.'); // 'C' for car, '.' for empty space } std::cout << std::endl; } // Function to simulate traffic flow void simulateTrafficFlow(std::vector<int>& road) { for (int step = 0; step < SIMULATION_STEPS; ++step) { std::vector<int> newRoad(ROAD_LENGTH, 0); // Move cars for (int i = 0; i < ROAD_LENGTH; ++i) { if (road[i] == 1) { int newPos = i + CAR_SPEED; if (newPos < ROAD_LENGTH) { newRoad[newPos] = 1; } } } road = newRoad; printRoad(road); std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Simulate time delay } } int main() { std::vector<int> road(ROAD_LENGTH, 0); // Initialize the road with empty spaces initializeRoad(road); // Place initial cars on the road std::cout << "Traffic Flow Simulation\n"; simulateTrafficFlow(road); return 0; } |
Explanation
- Constants:
ROAD_LENGTH
: The length of the road segment.INITIAL_CARS
: The number of cars placed on the road initially.CAR_SPEED
: The speed at which cars move (in units per time step).SIMULATION_STEPS
: Number of steps to simulate.
- initializeRoad Function:
- Initializes the road with cars. Places cars at the beginning of the road.
- printRoad Function:
- Prints the current state of the road. Cars are represented by ‘C’, and empty spaces by ‘.’.
- simulateTrafficFlow Function:
- Simulates the movement of cars over a number of steps.
- Movement: For each car, calculates its new position based on
CAR_SPEED
. Moves the car to its new position if it’s within the road length. - Updates the road state and prints it.
- Includes a delay to simulate real-time progression (
std::this_thread::sleep_for
).
- Main Function:
- Initializes the road and places the initial cars.
- Starts the traffic flow simulation and prints the results.
Usage
- Road Segment: The road is represented as a linear array where cars move from left to right.
- Car Movement: Cars move forward by
CAR_SPEED
units each step. - Simulation: Adjust the constants to modify the road length, number of cars, speed, and simulation duration.