#include <stdio.h>
#include <stdlib.h>

int main(){
	int x = 40;
	int y = 40;
 
        int board[x][y];
        int boardtemp[x][y];
	int n = 0;

        srand(time(NULL));

        for(int i = 0; i < x; i++){
                for(int j = 0; j < y; j++){
                        if(arc4random() > RAND_MAX / 2.0){
                                board[i][j] = 1;
                        } else {
                                board[i][j] = 0;
                        }
                }
        }

	for(int i = 0; i < x; i++){
		for(int j = 0; j < y; j++){
			boardtemp[i][j] = board[i][j];
		}
	} 
	
	while(1){
		system("clear");
		for(int i = 0; i < x; i++){
			for(int j = 0; j < y; j++){
				if(board[i][j]){
					printf(" #");
				} else {
					printf(" .");
				}
			}
			printf("\n");
		}

		for(int i = 0; i < x; i++){
			for(int j = 0; j < y; j++){
				for(int xshift = -1; xshift <= 1; xshift++){
					for(int yshift = -1; yshift <= 1; yshift++){
						if(xshift || yshift){
							/* indices wrap at board size */
							if(board[(i + xshift + x) % x][(j + yshift + y) % y]){
								n++;
							}
						}
					}
				}
				if(board[i][j]){
					if(n != 2 && n != 3){
						boardtemp[i][j] = 0;
					} 
				}
				if(n == 3 || n == 4){
					boardtemp[i][j] = 1;
				}
				
				n = 0;
			}
		}

		for(int i = 0; i < x; i++){
			for(int j = 0; j < y; j++){
				board[i][j] = boardtemp[i][j];
			}
		}
		sleep(1.0);
	}

	return 0;
}

