|
| 1 | +#include <iostream> |
| 2 | +#include <cstdio> |
| 3 | +#include <random> |
| 4 | +#include <chrono> |
| 5 | +#include <iostream> |
| 6 | +#include <algorithm> |
| 7 | +#include <vector> |
| 8 | +#include <thread> |
| 9 | + |
| 10 | +std::vector<int> initialize_cells(size_t n) { |
| 11 | + std::vector<int> cells(n); |
| 12 | + // std::mt19937 m{std::random_device{}()}; |
| 13 | + std::mt19937 m{0}; // fix the seed to ease debugging. |
| 14 | + std::uniform_int_distribution<int> u{0, 1}; |
| 15 | + for(int i = 0; i < cells.size(); ++i) { |
| 16 | + cells[i] = u(m); |
| 17 | + } |
| 18 | + return std::move(cells); |
| 19 | +} |
| 20 | + |
| 21 | +void print(const std::vector<int>& cells) { |
| 22 | + for(int i = 0; i < cells.size(); ++i) { |
| 23 | + std::cout << (cells[i] == 0 ? " " : "\u25A0"); |
| 24 | + } |
| 25 | + std::cout << std::endl; |
| 26 | +} |
| 27 | + |
| 28 | +void simulate_step(const std::vector<int>& current, std::vector<int>& next) { |
| 29 | + for(int i = 1; i < current.size()-1; ++i) { |
| 30 | + if(current[i] == 0) { |
| 31 | + next[i] = current[i-1]; |
| 32 | + } |
| 33 | + else { |
| 34 | + next[i] = current[i+1]; |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +int longest_queue(const std::vector<int>& cells) { |
| 40 | + int kmax = 0; |
| 41 | + int k = 0; |
| 42 | + for(int i = 0; i < cells.size(); ++i) { |
| 43 | + if(cells[i] == 1) { |
| 44 | + ++k; |
| 45 | + kmax = std::max(kmax, k); |
| 46 | + } |
| 47 | + else { |
| 48 | + k = 0; |
| 49 | + } |
| 50 | + } |
| 51 | + return kmax; |
| 52 | +} |
| 53 | + |
| 54 | +void simulate(size_t steps, std::vector<int>& current, std::vector<int>& next) { |
| 55 | + using namespace std::chrono_literals; |
| 56 | + std::mt19937 m{0}; // fixed seed to ease debugging. |
| 57 | + // std::uniform_int_distribution<int> d{0, 1}; |
| 58 | + std::discrete_distribution<> d({10, 90}); |
| 59 | + int lmax = 0; |
| 60 | + for(int i = 0; i < steps; ++i) { |
| 61 | + simulate_step(current, next); |
| 62 | + std::swap(current, next); |
| 63 | + lmax = std::max(lmax, longest_queue(current)); |
| 64 | + print(current); |
| 65 | + current[0] = d(m); // Next car, random. |
| 66 | + std::this_thread::sleep_for(1000ms); |
| 67 | + } |
| 68 | + std::cout << "Longest queue: " << lmax << std::endl; |
| 69 | +} |
| 70 | + |
| 71 | +int main(int argc, char** argv) { |
| 72 | + size_t n = 50; |
| 73 | + size_t steps = 50; |
| 74 | + std::vector<int> cells = initialize_cells(n); |
| 75 | + std::vector<int> next(n); |
| 76 | + simulate(steps, cells, next); |
| 77 | + return 0; |
| 78 | +} |
0 commit comments