summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGustav Sörnäs <gustav@sornas.net>2020-09-11 09:15:29 +0200
committerGustav Sörnäs <gustav@sornas.net>2020-09-11 09:19:24 +0200
commit00c12916c2d6d4ba7d0a7aa4072c46d1572402ee (patch)
tree1321f0ce2150ada81f019422856eb836c1244411
parentf906c5d984c5f39f7b9d152bb57fba8459914e22 (diff)
downloadtddd86-00c12916c2d6d4ba7d0a7aa4072c46d1572402ee.tar.gz
refactor main, better neighbour check
-rw-r--r--labb1/src/life.cpp62
1 files changed, 34 insertions, 28 deletions
diff --git a/labb1/src/life.cpp b/labb1/src/life.cpp
index 1f582f6..7233d79 100644
--- a/labb1/src/life.cpp
+++ b/labb1/src/life.cpp
@@ -8,6 +8,29 @@
#include <string>
/*
+ * Ask for a file and read it, storing the initial state in `grid`.
+ */
+void askAndReadFile(Grid<bool> &grid) {
+ std::string filepath;
+ std::cout << "file: ";
+ std::cin >> filepath;
+ std::ifstream input;
+ input.open(filepath);
+ int h, w;
+ input >> h >> w;
+ grid.resize(h, w);
+
+ for (int y = 0; y < grid.numRows(); y++) {
+ std::string line;
+ std::getline(input, line);
+ for (int x = 0; x < grid.numCols(); x++) {
+ grid.set(y, x, line[x] == 'X');
+ }
+ }
+ input.close();
+}
+
+/*
* Print a representation of the grid.
* Alive cells show as 'X', dead show as '-'.
*/
@@ -25,9 +48,9 @@ void printGrid(const Grid<bool> &grid) {
}
/*
- * Return 1 if (x, y) is in bounds and alive, otherwise 0.
+ * Return whether (x, y) is in bounds and alive.
*/
-int checkPoint(const Grid<bool> &grid, int y, int x) {
+bool checkPoint(const Grid<bool> &grid, int y, int x) {
return grid.inBounds(y, x) && grid.get(y, x) ? 1 : 0;
}
@@ -38,14 +61,14 @@ void simulate(Grid<bool> &grid) {
Grid<bool> prevGrid(grid);
for (int y = 0; y < grid.numRows(); y++) {
for (int x = 0; x < grid.numCols(); x++) {
- int numNeighbours = checkPoint(prevGrid, y-1, x-1) +
- checkPoint(prevGrid, y-1, x ) +
- checkPoint(prevGrid, y-1, x+1) +
- checkPoint(prevGrid, y , x-1) +
- checkPoint(prevGrid, y , x+1) +
- checkPoint(prevGrid, y+1, x-1) +
- checkPoint(prevGrid, y+1, x ) +
- checkPoint(prevGrid, y+1, x+1);
+ int numNeighbours = 0;
+ for (int dy = -1; dy <= 1; dy++) {
+ for (int dx = -1; dx <= 1; dx++) {
+ if ((dx != 0 || dy != 0) && checkPoint(prevGrid, y+dy, x+dx)) {
+ numNeighbours++;
+ }
+ }
+ }
if (numNeighbours < 2) {
grid.set(y, x, false);
} else if (numNeighbours == 2) {
@@ -61,24 +84,7 @@ void simulate(Grid<bool> &grid) {
int main() {
Grid<bool> grid;
-
- std::string filepath;
- std::cout << "file: ";
- std::cin >> filepath;
- std::ifstream input;
- input.open(filepath);
- int h, w;
- input >> h >> w;
- grid.resize(h, w);
-
- for (int y = 0; y < grid.numRows(); y++) {
- std::string line;
- std::getline(input, line);
- for (int x = 0; x < grid.numCols(); x++) {
- grid.set(y, x, line[x] == 'X');
- }
- }
- input.close();
+ askAndReadFile(grid);
char prompt;
bool running = true;