Game of Life NeighborCount help

I am quite stuck on trying to figure out how to write my code for counting neighbors in this Game of Life program I am attempting to write.

Requirements are as follow: Given two arguments that indicate the row and column of a particular cell in the matrix, this function returns the number of neighbors that have the value "true". Most positions in the grid have 8 neighbors like the center square in a tic-tac-toe game. The four corner positions have only 3 neighbors each. The remaining positions around the edge of the grid have 5 neighbors each.

Additional Requirement: In this function you must use your "get()" function to access the matrix, instead of accessing your 2D array data member directly. So, if your data member is named "m", you'll say "get(row, col)" instead of "m[row][col]". This will be a safer programming practice, since the get() function will do range checking for you (i.e., it will make sure that row and col are not out-of-bounds of the 2D array).

my boolMatrix Class

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
#ifndef LIFE_H
#define LIFE_H

#include <iostream>
#include <iomanip>
#include <cassert>
#include <fstream>

using namespace std;

class boolMatrix
{
public:
    static const int NUM_ROWS = 20; //Static variable declaring row size
    static const int NUM_COLS = 20; //Static variable declaring column size
    boolMatrix();   //A default constructor
    void set(int row,int col, bool val);
    void print() const; //observers
    bool get(int row,int col) const;
    int totalCount()const;
    int rowCount(int row)const;
    int colCount(int col)const;
    int neighborCount(int row, int col)const;
private:
    bool matrix[NUM_ROWS][NUM_COLS];

};

#endif


Two functions my problem is focusing on

1
2
3
4
5
 int boolMatrix::neighborCount(int row, int col)const
{

} 


1
2
3
4
5
bool boolMatrix::get(int row, int col) const
{
    assert(row>= 0 && row < NUM_ROWS && col >= 0 && col < NUM_COLS);
    return matrix[row][col];
}


I can provide a sample output and data file if needed.
Last edited on
It seems pretty straightforward.
What exactly is the problem?

1
2
3
4
5
6
int count = 0;
if (row > 0)            count += get(row - 1, col    );
if (row < NUM_ROWS - 1) count += get(row + 1, col    );
if (col > 0)            count += get(row    , col - 1);
if (col < NUM_COLS - 1) count += get(row    , col + 1);
// etc. 

Often when programming something like the game of life we put a border around the board so that we don't need to check the bounds. The border would always be false so it would never add to the count.
Last edited on
I could not think of how to begin the code, I had a general idea of how to setup an if else somewhat. When it comes to visualizing boundaries and a grid I think I struggle with that the most oppose to regular outputting and storing information like my past projects. Thank you for your help.
Topic archived. No new replies allowed.