-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameOfLife.java
90 lines (78 loc) · 2.81 KB
/
GameOfLife.java
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public class gameOfLife {
public static void main(String[] args)
{
int M = 10, N = 10;
// Intiliazing the grid.
int[][] grid = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
// Displaying the grid
System.out.println("Original Generation");
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
if (grid[i][j] == 0)
System.out.print(".");
else
System.out.print("*");
}
System.out.println();
}
System.out.println();
nextGeneration(grid, M, N);
}
// Function to print next generation
static void nextGeneration(int grid[][], int M, int N)
{
int[][] future = new int[M][N];
// Loop through every cell
for (int l = 1; l < M - 1; l++)
{
for (int m = 1; m < N - 1; m++)
{
// finding no Of Neighbours that are alive
int aliveNeighbours = 0;
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
aliveNeighbours += grid[l + i][m + j];
// The cell needs to be subtracted from
// its neighbours as it was counted before
aliveNeighbours -= grid[l][m];
// Implementing the Rules of Life
// Cell is lonely and dies
if ((grid[l][m] == 1) && (aliveNeighbours < 2))
future[l][m] = 0;
// Cell dies due to over population
else if ((grid[l][m] == 1) && (aliveNeighbours > 3))
future[l][m] = 0;
// A new cell is born
else if ((grid[l][m] == 0) && (aliveNeighbours == 3))
future[l][m] = 1;
// Remains the same
else
future[l][m] = grid[l][m];
}
}
System.out.println("Next Generation");
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
if (future[i][j] == 0)
System.out.print(".");
else
System.out.print("*");
}
System.out.println();
}
}
}