Tic-Tac-Toe game Abhinav and Anjali are playing the Tic-Tac-Toe game. Tic-Tac-Toe is a game played on a grid that's three squares by three squares. Abhinav is O, and Anjali is X. Players take turns putting their marks in empty squares. The first player to get 3 of her marks in a diagonal or horizontal, or vertical row is the winner. When all nine squares are complete, the game is over. If no player has three marks in a row, the game ends in a tie. Write a program to decide the winner in the Tic-Tac-Toe game. Input The input will be three lines contain O's and X's separated by space. Output The output should be a single line containing either "Abhinav Wins" or "Anjali Wins" or "Tie". Explanation For example, if the input is O X O O X X O O X as three of O's are in vertical row print "Abhinav Wins". Sample Input 1 O X O O X X O O X Sample Output 1 Abhinav Wins Sample Input 2 O O X X X O X O O Sample Output 2 Anjali Wins i want exact sample outputs sir
public class Main {
public static boolean isWin(String[][] board, String symbol) {
boolean win;
for (int i = 0; i < board.length; i++) {
win = true;
for (int j = 0; j < board[i].length; j++) {
if (!board[i][j].equals(symbol)) {
win = false;
break;
}
}
if (win) {
return true;
}
win = true;
for (int j = 0; j < board.length; j++) {
if (!board[j][i].equals(symbol)) {
win = false;
break;
}
}
if (win) {
return true;
}
}
win = true;
boolean rToL = true;
for (int i = 0, j = board.length - 1; i < board.length; i++, j--) {
if (!board[i][i].equals(symbol)) {
win = false;
}
if (!board[i][j].equals(symbol)) {
rToL = false;
}
}
return win || rToL;
}
public static String findWinner(String lineOne, String lineTwo, String lineThree) {
String[][] board = {lineOne.split(" "), lineTwo.split(" "), lineThree.split(" ")};
return isWin(board, "O") ? "Abhinav Wins" : isWin(board, "X") ? "Anjali Wins" : "Tie";
}
public static void main(String[] args) {
System.out.println(findWinner("O X O", "O X X", "O O X"));
System.out.println(findWinner("O X O", "O X X", "O O X"));
System.out.println(findWinner("O O X", "X X O", "X O O"));
}
}
Comments
Leave a comment