Conway's Game of Life Update(Next Generation)

我与影子孤独终老i 提交于 2019-12-02 06:30:15

It looks like you are trying to modify the same grid you are looping through. As you loop through your grid, changes should be made based on the previous state of the grid. Try constructing a new grid instead of writing over the old one.

That's how I would go about it. Note that this is C++11 implementation

template<std::size_t X, std::size_t Y>
class GameOfLife {
private: 
  std::pair<int, int> neighbors[8];

public:
  typedef std::array<std::array<uint16_t,Y>,X> Grid;

private:
  uint16_t getCellStatus(Grid const& conway, int x, int y) {        
    uint16_t liveCount = 0;     
    for(auto&& neighbor: neighbors) {
      int nX = x + neighbor.first;
      int nY = y + neighbor.second;
      if(nX>=0 && nX<X && nY>=0 && nY<Y){
        if(conway[nX][nY]>0) liveCount++;
      }     
    }
    if(conway[x][y]>0){
      if(liveCount==2 ||liveCount == 3) return 1;        
    } 
    else {
      if(liveCount==3) return 1;        
    }
    return 0;
    }

public: 
  GameOfLife() {
    size_t index = 0;
    for(int i=-1; i<=1; ++i) {
      for(int j=-1; j<=1; ++j){
        if((i|j)==0) continue;
        neighbors[index].first = i;
        neighbors[index++].second = j;
      }             
    }
  }

  Grid getNextConway(Grid const& conway) {
    Grid output;
    for(size_t i=0; i<X; ++i)
      for(size_t j=0; j<Y; ++j) output[i][j]=getCellStatus(conway,i,j);
      return output;
  }

  Grid printGrid(Grid const& conway) { 
    for (int i = 0; i < X; ++i){
      for (int j = 0; j < Y; ++j) {
        if(conway[i][j]==0) std::cout<<"0";
        else std::cout<<"1";
      }
      std::cout<<std::endl;
    }
    std::cout<<std::endl;
  } 

};


int main() {
  size_t const DIM = 8;
  size_t const NUM_GENS = 10;
  typedef GameOfLife<DIM,DIM> Game;
  typename Game::Grid gameGrid;  
  for (int i = 0; i < DIM; ++i) {    
    for (int j = 0; j < DIM; ++j) {
      gameGrid[i][j] = rand()%2;
    }
  }
  Game conway;
  conway.printGrid(gameGrid);  
  for (int i = 0; i < NUM_GENS; ++i) {
    gameGrid = conway.getNextConway(gameGrid);
    conway.printGrid(gameGrid);
  }
  return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!