Software AG Interview Question for Java Developers


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 3 vote

Here is the fully working Java code for 1 player vs computer Tic Tac Toe game.
Compile it. Run it!

import java.util.Random;
import java.util.Scanner;
import java.io.*;
class Player
{
	private int score;
	private String name;
	Player()
	{
		name="Unknown";
		score=0;
	}
	Player(String name)
	{
		this.name=name;
		score=0;
	}
	public void addScore(int add)
	{
		score+=add;
	}
	public int getScore()
	{
		return score;
	}
	public String getName()
	{
		return name;
	}
}
class Board
{
	private final int size=3;
	private boolean gameOver;
	private boolean win;
	private int noOfMoves;
	private char[][] matrix=new char[size][size];
	Board()
	{
		int i,j;
		for(i=0;i<size;i++)
			for(j=0;j<size;j++)
				matrix[i][j]='.';
		gameOver=false;
		win=false;
		noOfMoves=0;
	}
	public void show()
	{
		int i,j;
		for(i=0;i<size;i++)
		{
			for(j=0;j<size;j++)
				System.out.print(" "+matrix[i][j]);			
			System.out.println();
		}
		System.out.println();
	}
	public boolean isGameOver()
	{
		return gameOver;
	}
	public boolean won()
	{
		return win;
	}
	public int playerMove(int x,int y)//1 player game against Computer
	{
		if(x<0 || y<0 ||x>=size || y>=size)
			return -1;//invalid move;
		if(matrix[x][y]=='O' || matrix[x][y]=='X')
			return -1;//invalid move
		matrix[x][y]='X';
		noOfMoves++;
		return 0;
	}
	public void computerMove()//1 player game against Computer
	{	//random move
		Random rand=new Random();
		int x,y;
		x=rand.nextInt(size);
		y=rand.nextInt(size);
		while(matrix[x][y]=='X' || matrix[x][y]=='O')
		{
			x=rand.nextInt(size);
			y=rand.nextInt(size);
		}
		matrix[x][y]='O';
		noOfMoves++;
	}
	public void setWon(char c)
	{
		if(c=='.')
			return;
		if(c=='X')
			win=true;
		else
			win=false;
		gameOver=true;
	}
	public void check()
	{
		int i,j;
		boolean f;
		for(i=0;i<size;i++)
		{
			j=1;
			if(matrix[i][0]!='.')
				for(;j<size;j++)//ith row check
					if(matrix[i][j]!=matrix[i][j-1])
						break;
			if(j==size)
			{
				System.out.println("row "+i+" crossed");
				setWon(matrix[i][0]);
				return;
			}
			j=1;
			if(matrix[0][i]!='.')
				for(;j<size;j++)//ith column check
					if(matrix[j][i]!=matrix[j-1][i])
						break;
			if(j==size)
			{
				System.out.println("col "+i+" crossed");
				setWon(matrix[0][i]);
				return;
			}
		}
		//diagonals
		i=1;
		if(matrix[0][0]!='.')
		for(;i<size;i++)
			if(matrix[i][i]!=matrix[i-1][i-1])
				break;
		if(i==size)
		{
			System.out.println("first diagonal "+i+" crossed");
			setWon(matrix[0][0]);
			return;
		}
		i=1;
		if(matrix[0][size-1]!='.')
		for(;i<size;i++)
			if(matrix[i][size-1-i]!=matrix[i-1][size-i])
				break;
		if(i==size)
		{
			System.out.println("second diagonal "+i+" crossed");
			setWon(matrix[0][size-1]);
			return;
		}
		if(noOfMoves>=size*size)
		{
			gameOver=true;
			win=false;
		}
		return;
	}
}
class TTT
{
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		Board board=new Board();
		Player player=new Player();
		int x,y;
		while(!board.isGameOver())
		{
			board.show();
			x=sc.nextInt();
			y=sc.nextInt();
			while(board.playerMove(x,y)==-1)
			{
				System.out.println("Invalid input. Enter again!");
				x=sc.nextInt();
				y=sc.nextInt();		
			}
			board.check();
			if(!board.isGameOver())
			{
				board.computerMove();
				board.check();
			}
		}
		board.show();
		if(board.won())
			System.out.println("Congrats! You won!!!!");
		else
			System.out.println("You lose! Go practice some more.");
	}
}

- neerajlakhotia08 July 09, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Is it asked to create a "computer move" ? I think this may waste precious interview time.

- coolraj334 December 03, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Winner will be declared in constant time, no need to run loops to check winner on each move.

//This is main class to run a sample case
public class TicTacToeSample {
	public static void main(String[] args) {
		try {
			final Board board = new Board(3);
			Player X = new Player("X", board);
			Player Y = new Player("Y", board);
			
			X.takePosition(0, 0);
			Y.takePosition(1, 1);
			X.takePosition(2, 0);
			Y.takePosition(2, 0);
			Y.takePosition(1, 0);
			X.takePosition(2, 2);
			Y.takePosition(1, 2);
			X.takePosition(2, 1);
		} catch (WinnerException e) {
			System.out.println(e.getMessage());
		}
	}
}

class Board{

	private final Player[][] board;
	private final int size;
	public Board(int size){
		this.size = size;
		this.board = new Player[size][size];
	}	
	public int getRows() {
		return size;
	}
	public int getCols() {
		return size;
	}
	public int getDiagonals() {
		return 2;
	}
	public void setOnwer(Player player, int row, int col) throws IllegalStateException {
		if(board[row][col] == null){
			board[row][col] = player;
		}else{
			throw new IllegalStateException("Position already taken by player " + board[row][col]);
		}		
	}
	public Player getOnwer(int row, int col) {
		return board[row][col];
	}
	public int totalPositions() {
		return size;
	}
	
}

@SuppressWarnings("serial")
class WinnerException extends Exception{
	public WinnerException(String msg) {
		super(msg);
	}	
}

class Player{	
	private final String name;	
	private final Board board;	
	private final int[] rows;
	private final int[] cols;
	private final int[] diagonal;
	
	public Player(String name, Board board){
		this.name = name;
		this.board = board;
		this.rows = new int[board.getRows()];
		this.cols = new int[board.getCols()];
		this.diagonal = new int[2];
	}

	@Override
	public String toString() {
		return name;
	}

	public void takePosition(int row, int col) throws WinnerException {
		board.setOnwer(this, row, col);

		if(++rows[row] == board.totalPositions()){
			throw new WinnerException("Game winner is player " + this + " taken complete row " + row );
		}
		if(++cols[col] == board.totalPositions()){
			throw new WinnerException("Game winner is player " + this + " taken complete column " + row );		
		}
		if(row == col){
			if(++diagonal[0] == board.totalPositions()){
				throw new WinnerException("Game winner is player " + this + " taken complete diagonal left");
			}
		}
		if(row + col + 1 == board.totalPositions()){
			if(++diagonal[1] == board.totalPositions()){
				throw new WinnerException("Game winner is player " + this + " taken complete diagonal right");
			}
		}

	}
		
}

- kainm July 10, 2014 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More