Skip to content

Instantly share code, notes, and snippets.

@youssef3wi
Created January 29, 2024 17:17
Show Gist options
  • Select an option

  • Save youssef3wi/77a55bdc6eb63948c3ebd9003759bc9f to your computer and use it in GitHub Desktop.

Select an option

Save youssef3wi/77a55bdc6eb63948c3ebd9003759bc9f to your computer and use it in GitHub Desktop.
Tic-tac-toe or noughts and crosses is a childhood game where players take turns playing X's and O's on a 3x3 board.
import java.util.Scanner;
/**
* Tic-tac-toe or noughts and crosses is a childhood game where players take turns playing X's and O's
* on a 3x3 board trying to get three in a row. Here's an example game where O is victorious:
* <p>
* Write a function that takes an NxN game board as input and returns true or false depending on whether it's a valid board.
* The valid states for squares of the board are "X", "O", and "~" (no one has played there yet).<br>
* Examples of valid boards:
* <ol style="margin-top: 0">
* <li>A board with a game in progress</li>
* <li> A board where there is a winner.</li>
* </ol>
* <p>
* Examples of invalid boards:
* <ol style="margin-top: 0">
* <li>One where one player has played more than another player (excluding the case where X has played, and it's O's turn)</li>
* </ol>
* NOTE: In our variation of the game, X is always the first player to play.
* <p>
* INPUT
* <ul style="margin-top: 0">
* <li>Line 1: N the size of the board</li>
* <li>Line 2: N states of the first line</li>
* <li>...</li>
* <li>Line N+1: N states of the Nth line</li>
* </ul>
* <p>
* OUTPUT:
* True if the board is valid otherwise False.
* <p>
* CONSTRAINTS:
* 0 < N < 1000
* <p>
* EXAMPLE:
* <table border="1" style="border: 1px solid black; border-collapse: collapse;">
* <tr>
* <td>Input</td>
* <td>Output</td>
* </tr>
*
* <tr>
* <td>3</td>
* <td>True</td>
* </tr>
* <tr>
* <td>XOO</td>
* </tr>
* <tr>
* <td>OXX</td>
* </tr>
* <tr>
* <td>OXX</td>
* </tr>
* </table>
*/
public class TicTacToe {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if (in.hasNextLine()) {
in.nextLine();
}
int xPlays = 0, oPlays = 0;
String[] board = new String[n];
for (int i = 0; i < n; i++) {
String line = in.nextLine();
// store
board[i] = line;
// process
for (int idx = 0; idx < line.length(); idx++) {
if (line.charAt(idx) == 'O') {
oPlays++;
} else if (line.charAt(idx) == 'X') {
xPlays++;
}
}
}
// Check
if (xPlays >= 1 && board[0].charAt(0) == 'X' // X is always the first player to play.
&& (
xPlays == oPlays ||
(xPlays > oPlays && oPlays + 1 == xPlays) ||
(oPlays > xPlays && xPlays + 1 == oPlays)
)
) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment