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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include <chrono>
#include <iomanip>
#include <iostream>
#include <limits>
#include <random>
#include <sstream>
#include <string>
#include <vector>
struct PosOnScreen {
char empty,
filled,
current;
int visited;
PosOnScreen() : empty { '.' }, filled { '*' }, current { empty }, visited { 0 } {}
friend std::ostream& operator<<(std::ostream& os, const PosOnScreen& rhs)
{ return os << rhs.current; }
};
struct Point {
int x, // columns
y; // rows
Point() : x {}, y {} {}
Point(int x_arg, int y_arg) : x {x_arg}, y {y_arg} {}
};
void displayGrid(const std::vector<std::vector<PosOnScreen>>& v);
void displayVisitedGrid(const std::vector<std::vector<PosOnScreen>>& v);
void waitForEnter();
int main()
{
std::cout << "What are the dimensions of the grid (rows x columns)?\n"
"Please type 2 numbers and press ENTER: ";
std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
int rows {}, cols{};
iss >> rows >> cols;
std::vector<std::vector<PosOnScreen>> grid(rows, std::vector<PosOnScreen>(cols));
std::mt19937 rng(std::chrono::high_resolution_clock::now().time_since_epoch().count());
std::uniform_int_distribution<> rrow(0, rows-1);
std::uniform_int_distribution<> rcol(0, cols-1);
// Decide initial position:
Point pos { rcol(rng), rrow(rng) };
grid.at(pos.y).at(pos.x).current = grid.at(pos.y).at(pos.x).filled;
grid.at(pos.y).at(pos.x).visited++;
displayGrid(grid);
std::cout << "\nHow many movements do you want to simulate? ";
std::getline(std::cin, line);
iss.clear();
iss.str(line);
int moves {};
iss >> moves;
for(int i{}; i<moves; ++i) {
grid.at(pos.y).at(pos.x).current = grid.at(pos.y).at(pos.x).empty;
pos.x = rcol(rng);
pos.y = rrow(rng);
grid.at(pos.y).at(pos.x).current = grid.at(pos.y).at(pos.x).filled;
grid.at(pos.y).at(pos.x).visited++;
// Uncomment the following lines to check every movement
// displayGrid(grid);
// waitForEnter();
}
displayVisitedGrid(grid);
waitForEnter();
return 0;
}
void displayGrid(const std::vector<std::vector<PosOnScreen>>& v)
{
for(const auto& ve : v) {
for(const auto& p : ve) { std::cout << p; }
std::cout << '\n';
}
}
void displayVisitedGrid(const std::vector<std::vector<PosOnScreen>>& v)
{
for(const auto& ve : v) {
for(const auto& p : ve) { std::cout << std::setw(4) << p.visited; }
std::cout << '\n';
}
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
|