clueless coding // TODO: be smarter

LeetCode Game of Life: CPP Solution



TL;DR Code Solution



int findLiveNeighbors(vector<vector<int>>& board, int i, int j) {
    int count = 0;
    int mask = 1;
    if (i > 0) count += board[i-1][j] & mask;
    if (j > 0) count += board[i][j-1] & mask;
    if (i < (int)board.size() - 1) count += board[i + 1][j] & mask;
    if (j < (int)board[0].size() - 1) count += board[i][j + 1] & mask;
    if (i > 0 && j > 0) count += board[i - 1][j - 1] & mask;
    if (i > 0 && j < (int)board[0].size() - 1) count += board[i-1][j+1] & mask;
    if (i < (int)board.size() - 1 && j > 0) count += board[i+1][j-1] & mask;
    if (i < (int)board.size() - 1 && j < (int)board[0].size() - 1) count += board[i+1][j+1] & mask;
    return count;
}

void gameOfLife(vector<vector<int>>& board) {

    for (int i = 0; i < board.size(); i++) {
        for (int j = 0; j < board[0].size(); j++) {
            int neighbors = findLiveNeighbors(board, i, j);
            cout << neighbors;
            if (board[i][j] == 0 && neighbors == 3) {
                board[i][j] |= 2;
            }
            if (board[i][j] == 1 && (neighbors == 2 || neighbors == 3)) {
                board[i][j] |= 2;
            }
        }
    }

    for (int i = 0; i < board.size(); i++) {
        for (int j = 0; j < board[0].size(); j++) {
            board[i][j] = board[i][j] >> 1;
        }
    }

}