Skip to content

Commit

Permalink
optimized game of life
Browse files Browse the repository at this point in the history
  • Loading branch information
Sherali Obidov committed Jun 29, 2018
1 parent 0c66245 commit 8870c55
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 18 deletions.
2 changes: 2 additions & 0 deletions src/problems/medium/ContainerWithMostWater.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package problems.medium;

import java.util.*;

/**
* Why Did you create this class? what does it do?
*/
Expand Down
56 changes: 38 additions & 18 deletions src/problems/medium/GameofLife.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,57 @@
* Created by sherxon on 1/28/17.
*/
public class GameofLife {
static void gameOfLife(int[][] a) {
public void gameOfLife(int[][] a) {
if (a == null || a.length == 0)
return;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
int al = getAliveN(a, i, j);
if (a[i][j] == 1 && (al < 2 || al > 3))
int count = count(a, i, j);
if (isAlive(a, i, j) && count < 2)
a[i][j] = -1;
else if (a[i][j] == 0 && al == 3)
a[i][j] = 2;
else if (isAlive(a, i, j) && count > 3)
a[i][j] = -1;
else if (isAlive(a, i, j))
a[i][j] = 1;
else if (!isAlive(a, i, j) && count == 3)
a[i][j] = -2;
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] == -1) a[i][j] = 0;
else if (a[i][j] == 2) a[i][j] = 1;
if (a[i][j] == -1)
a[i][j] = 0;
else if (a[i][j] == -2)
a[i][j] = 1;
}
}

}

private static int getAliveN(int[][] a, int i, int j) {
int count = 0;
if (j < a[i].length - 1 && (a[i][j + 1] == 1 || a[i][j + 1] == -1)) count++;
if (j > 0 && (a[i][j - 1] == 1 || a[i][j - 1] == -1)) count++;
if (i > 0 && (a[i - 1][j] == 1 || a[i - 1][j] == -1)) count++;
if (i < a.length - 1 && (a[i + 1][j] == 1 || a[i + 1][j] == -1)) count++;

if (i < a.length - 1 && j < a[i].length - 1 && (a[i + 1][j + 1] == 1 || a[i + 1][j + 1] == -1)) count++;
if (i < a.length - 1 && j > 0 && (a[i + 1][j - 1] == 1 || a[i + 1][j - 1] == -1)) count++;
if (i > 0 && j > 0 && (a[i - 1][j - 1] == 1 || a[i - 1][j - 1] == -1)) count++;
if (i > 0 && j < a[i].length - 1 && (a[i - 1][j + 1] == 1 || a[i - 1][j + 1] == -1)) count++;
boolean isAlive(int[][] a, int i, int j) {
if (i < 0 || j < 0 || i >= a.length || j >= a[i].length)
return false;
return a[i][j] == 1 || a[i][j] == -1;
}

int count(int[][] a, int i, int j) {
int count = 0;
if (isAlive(a, i - 1, j - 1))
count++;
if (isAlive(a, i - 1, j))
count++;
if (isAlive(a, i - 1, j + 1))
count++;
if (isAlive(a, i, j - 1))
count++;
if (isAlive(a, i, j + 1))
count++;
if (isAlive(a, i + 1, j - 1))
count++;
if (isAlive(a, i + 1, j))
count++;
if (isAlive(a, i + 1, j + 1))
count++;
return count;
}
}

0 comments on commit 8870c55

Please sign in to comment.