Expedia Interview Question
SDE-2sCountry: United States
Interview Type: In-Person
public class TicTacToeGame {
private static final int SIZE = 3;
private char[][] matrix;
private boolean player = true;
private boolean flag = false;
public TicTacToeGame() {
matrix = new char[SIZE][SIZE];
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
matrix[row][col] = '-';
}
}
}
public void play(int row, int column) {
if ('-' == matrix[row][column] && !flag) {
matrix[row][column] = (player ? 'x' : '0');
player = !player;
if (checkWin()) {
System.out.println((player ? "First " : "Second") + " Player win");
printMatrix();
flag = true;
}
return;
}
if (flag) {
System.out.println((player ? "First " : "Second") + " Player winned ");
}
System.out.println("invalid move");
return;
}
private char move() {
return (player ? 'x' : '0');
}
private boolean checkWin() {
return (checkWinConditionInRow() || checkWinConditionInColumn() || checkWinConditionInDiagonal());
}
private boolean checkWinConditionInRow() {
for (int row = 0; row < SIZE; row++) {
boolean isValid = true;
for (int col = 0; col < SIZE; col++) {
if (matrix[row][col] != move()) {
isValid = false;
break;
}
}
if (isValid) {
return true;
}
}
return false;
}
private boolean checkWinConditionInColumn() {
for (int col = 0; col < SIZE; col++) {
boolean isValid = true;
for (int row = 0; row < SIZE; row++) {
if (matrix[row][col] != move()) {
isValid = false;
break;
}
}
if (isValid) {
return true;
}
}
return false;
}
private boolean checkWinConditionInDiagonal() {
return ((matrix[0][0] == move() && matrix[1][1] == move() && matrix[2][2] == move()) || (matrix[0][2] == move()
&& matrix[1][1] == move() && matrix[2][0] == move()));
}
private void printMatrix() {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
public static void main(String args[]) {
TicTacToeGame ticTacToeGame = new TicTacToeGame();
ticTacToeGame.play(0, 0);
ticTacToeGame.play(1, 1);
ticTacToeGame.play(0, 1);
ticTacToeGame.play(1, 2);
ticTacToeGame.play(0, 2);
ticTacToeGame.play(2, 0);
}
}
- Vir Pratap Uttam May 23, 2015