Tuesday 24 May 2016

Write a function to figure out if someone has won in a game of tic-tac-toe.


public class TicTacToe {
 public static boolean isWon(char board[][]) {
  if (board.length != 3 || board[0].length != 3) {
   throw new IllegalArgumentException("Wrong Game");
  }

  for (int i = 0; i < 3; i++) {
   if (checkRow(board, i))
    return true;

   if (checkColumn(board, i))
    return true;
  }

  if (checkDiagonals(board)) {
   return true;
  }
  return false;
 }

 private static boolean checkRow(char board[][], int row) {
  if (board[row][0] == board[row][1] && board[row][1] == board[row][2])
   return true;

  return false;
 }

 private static boolean checkColumn(char board[][], int column) {
  if (board[0][column] == board[1][column]
    && board[1][column] == board[2][column])
   return true;
  return false;
 }

 private static boolean checkDiagonals(char board[][]) {
  if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
   return true;

  if (board[2][0] == board[1][1] && board[1][1] == board[0][2])
   return true;

  return false;
 }
}


import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TicTacToeTest {

 @Test
 public void test1() {
  char[][] board1 = new char[][] { { 'X', 'X', 'X' }, { 'O', 'X', 'O' },
    { 'X', 'O', 'O' } };

  char[][] board2 = new char[][] { { 'X', 'O', 'X' }, { 'X', 'X', 'O' },
    { 'X', 'O', 'O' } };

  char[][] board3 = new char[][] { { 'X', 'O', 'O' }, { 'O', 'X', 'O' },
    { 'X', 'O', 'X' } };

  char[][] board4 = new char[][] { { 'X', 'O', 'X' }, { 'O', 'O', 'X' },
    { 'X', 'X', 'O' } };

  char[][] board5 = new char[][] { { 'X', 'O', 'O' }, { 'O', 'X', 'O' },
    { 'X', 'O', 'O' } };

  assertTrue(TicTacToe.isWon(board1));
  assertTrue(TicTacToe.isWon(board2));
  assertTrue(TicTacToe.isWon(board3));
  assertFalse(TicTacToe.isWon(board4));
  assertTrue(TicTacToe.isWon(board5));
 }
}

No comments:

Post a Comment