Google Interview Question
1,220 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Google:
Game of Life - write a function to calculate next state of the board based on current state
| Tags: | data structures, algorithm See more , See less 8 |
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (5)
1 of 1 people found this helpful
Helpful Answer?
Yes |
No
Inappropriate?
package com.google.interview2;
import java.util.Random;
public class GameOfLife {
public static void gameOfLift(int[][] game){
for (int i=0; i<game.length; ++i){
for (int j=0; j<game.length; ++j){
int numOfNeigh = howMuchNeigh(game, i, j);
if (game[i][j]==1 && (numOfNeigh == 0 || numOfNeigh == 1)){
game[i][j] = 0;
}
if (game[i][j]==1 && numOfNeigh > 3){
game[i][j] = 0;
}
if (game[i][j]==0 && numOfNeigh == 3){
game[i][j] = 1;
}
}
}
}
public static int howMuchNeigh(int[][] game, int i, int j){
int starti,endi,startj,endj;
if (i > 0){
starti = i-1;
}
else{
starti = i;
}
if (i < game.length-1){
endi = i+1;
}
else{
endi=i;
}
if (j > 0){
startj = j-1;
}
else{
startj = j;
}
if (j < game.length-1){
endj = j+1;
}
else{
endj=j;
}
int numOfneigh=0;
for (int ind = starti; ind <=endi; ++ind){
for (int ind2 = startj; ind2 <=endj; ++ind2){
if (game[ind][ind2] == 1 && !(ind==i && ind2==j)){
++numOfneigh;
}
}
}
return numOfneigh;
}
public static void main(String[] args) {
int[][] game = new int[5][5];
Random generator = new Random();
for (int i=0; i<10; ++i){
int ind =generator.nextInt(5);
int ind2 =generator.nextInt(5);
game[ind][ind2] = 1;
}
for(int i=0; i<5; ++i){
for (int j=0; j<5; ++j){
System.out.print(game[i][j]+" ");
}
System.out.println();
}
gameOfLift(game);
System.out.println("after one round");
for(int i=0; i<5; ++i){
for (int j=0; j<5; ++j){
System.out.print(game[i][j]+" ");
}
System.out.println();
}
gameOfLift(game);
System.out.println("after second round");
for(int i=0; i<5; ++i){
for (int j=0; j<5; ++j){
System.out.print(game[i][j]+" ");
}
System.out.println();
}
gameOfLift(game);
System.out.println("after third round");
for(int i=0; i<5; ++i){
for (int j=0; j<5; ++j){
System.out.print(game[i][j]+" ");
}
System.out.println();
}
}
}
Helpful Answer?
Yes |
No
Inappropriate?
Helpful Answer?
Yes |
No
Inappropriate?
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up
0 of 0 people found this helpful
by Steve: