I'm trying to finish up this Game of Life project I have started. I've read multiple posts on creating a toroidal (wrap-around) grid and have attempted to do the same, but I'm not too sure I've got the correct solution.
It was recommended to me to use (i-1)%size for wrapping rows, but I don't really understand why, nor do I think I'm using it correctly. Could someone provide some insight into this, or possibly offer an alternative?
vector<string> nextState(long row, long col, vector<string> table,
vector<string> newTable, vector<long> birth, vector<long> survive) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
long Alivecell = 0;
// Count live neighbors of particular cell
// Wrap rows if index out of range
if (table[(i-1) % table.size()][j-1] == '#') {
Alivecell++;
}
if (table[(i-1) % table.size()][j] == '#') {
Alivecell++;
}
if (table[(i-1) % table.size()][j+1] == '#') {
Alivecell++;
}
if (table[i][j-1] == '#') {
Alivecell++;
}
if (table[i][j+1] == '#') {
Alivecell++;
}
if (table[i+1][j-1] == '#') {
Alivecell++;
}
if (table[i+1][j+1] == '#') {
Alivecell++;
}
if (table[i+1][j] == '#') {
Alivecell++;
}
// Check rules for cell birth/survival/death
newTable[i][j] = '.';
if (table[i][j] == '#' && Alivecell <= 1) {
newTable[i][j]='.'; // Death
}
else if (table[i][j] == '#' && Alivecell >= 4) {
newTable[i][j] = '.'; // Death
}
else if (table[i][j] == '.' && Alivecell == 3) {
newTable[i][j]= '#'; // Birth
}
else if (table[i][j] == '#' &&
(Alivecell == 2 || Alivecell == 3 )) {
newTable[i][j] = '#'; // Survive
}
}
}
return newTable;
}
Aucun commentaire:
Enregistrer un commentaire