I'm kinda stuck on what to do with this square matrix coding project.
Whenever I try to input any values, the results always turn out as true and that the square matrix is a magic square. For example, this would turn out true:
16 03 02 13
05 10 11 08
09 06 07 12
04 15 14 01
but when I input values like:
03 04 16 02
05 01 02 10
05 08 07 12
03 14 13 09
This should return false but it still returns true saying that it is a magic square.
The requirements are that I need all the methods
"public void add(int i, int row, int col)": Adds an integer to the matrix at the specified location.
public
"public boolean allInRange": Determines whether all values in the matrix are in the proper range
"public boolean allUnique": Determines whether all values in the matrix appear only once
"public boolean isMagic": Determines whether the matrix illustrates a magic square. This means:
The user entered n^2 numbers for some number n
The numbers are only between 1 and n^2, inclusive
Each of the numbers occurs exactly once in the matrix
The sums of the elements in each row, column, and the two diagonals are equal
public class SquareMatrix {
private int[][] array;
public SquareMatrix(int size)
{
array = new int[size][size];
}
public void add(int i, int row, int column) {array[row][column] = i;}
//Just checks if the #of rows & columns are between 1-n^2
public boolean allInRange()
{
int n = array.length;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < array[row].length; col++)
{
if (array[row][col] < 1 || array[row][col] > n*n)
return false;
}
}
return true;
}
public boolean allUnique()
{
for (int i =0; i < array.length - 1; i++)
{
for (int j = i + 1; j < array.length; j++)
{
if(array[i]==array[j])
return false;
}
}
return true;
}
//Supposed to call the other methods (allInRange & allUnique)
public boolean isMagic()
{
for(int[] row : array)
{
for (int num : row)
{
if (num == 0)
return false;
}
}
boolean range = allInRange();
if (range == true)
return true;
if (range == false)
return false;
boolean unique = allUnique();
if (unique == true)
return true;
if (unique == false)
return false;
int sumRow;
int sumCol;
int sum1 = 0;
int sum2 = 0;
//Sum of Left to Right Diaganol
for (int i = 0; i < array.length; i++)
{
sum1 += array[i][i];
}
//sum of right to left diaganol
for (int j = 0; j < array.length; j++)
{
sum2 += array[j][array.length-1-j];
}
if (sum1 != sum2)
return false;
//Sum of Rows
for (int row = 0; row < array.length; row++)
{
sumRow = 0;
for (int col = 0; col < array[row].length; col++)
sumRow += array[row][col];
if (sumRow != sum1)
return false;
}
//Sum of Col
for (int i = 0; i < array.length; i++)
{
sumCol = 0;
for (int j = 0; j < array.length; j++)
sumCol = array[j][i];
if (sumCol != sum1)
return false;
}
return true;
}
public String toString()
{
int n = array.length;
String lol = "";
for (int[] row : array)
{
for (int num : row)
{
String hi = String.format("%0"+(n*n+"").length()+"d",num);
lol += hi + " ";
}
lol += "\n";
}
return lol;
}
}
Here is my driver class
import javax.swing.*;
public class SquareMatrixDriver {
public static void main(String[] args) { //My favorite line in history
JFrame bot = new JFrame(); //We can use JFrame to read the inputs
do
{
//We have to make sure that it is a valid input or else I am doomed
int size = 0;
do
{
size = Integer.parseInt(JOptionPane.showInputDialog(bot, "Enter the size of the matrix."));
if (size < 1)
{
JOptionPane.showMessageDialog(bot, "Invalid size! Enter a number greater than 0.");
}
}
while(size < 1);
SquareMatrix matrix = new SquareMatrix(size);
for (int i=0; i<size; i++)
{
//Gets thhe User's Input
String[] stringInput;
do
{
stringInput = JOptionPane.showInputDialog(bot, "Enter the row number" + (i + 1) + ", with " + size + " elements, split by commas.").split(",");
if (stringInput.length != size)
{ //In this code we basically enter the numbers with commas
JOptionPane.showMessageDialog(bot, "Invalid size! " + stringInput.length + " elements entered but " + size + " required.");
}
}
while(stringInput.length != size);
int[] intInput = new int[size];
for (int o=0; o<size; o++)
{
}
for (int o=0; o<size; o++)
{
matrix.add(Integer.parseInt(stringInput[o]), i, o); //Here we would put everything into the Matrix
}
}
JOptionPane.showMessageDialog(bot, "The matrix is " + (matrix.isMagic()? "very" : "not") + " correct"); //This line will output if the Matrix works or doesnt work
JOptionPane.showMessageDialog(bot, matrix); // Enters out the final output
} while (JOptionPane.showConfirmDialog(bot, "Do you wish to exit?", "Exit", JOptionPane.YES_NO_OPTION) == 1); //Asks the User if they would like to exit the program
}
}
Errors that I could find by visual inspection:
allUnique() is completely wrong, you have to check if each number occurs only once in the matrix, but you are comparing row arrays that is something totally different, the best way to check unicity would be normally to use an hashset, but since here you have a very defined range of numbers (from 1 to n2), then use any array of n2 booleans. Scan the square matrix and test/set the corresponding element in the array, if already set return false.
public boolean allUnique() {
int n=array.length;
boolean[] set=new boolean[n*n];
for (int i=0; i < n; i++) {
for (int j=0;j < n; j++) {
//Here assuming that you already sucessfully called allInRange,
//otherwise we must check bounds to avoid an index out of bounds exception
if(set[array[i][j]-1]) {
return false;
}
set[array[i][j]-1] = true;
}
}
return true;
}
In method isMagic() all this part is wrong and redundant
boolean range = allInRange();
if (range == true)
return true; //WRONG, this will immediately return with true, without further checks
if (range == false)
return false;
boolean unique = allUnique();
if (unique == true)
return true; //WRONG, same as before
if (unique == false)
return false;
Just replace it with
if (!allInRange()) {
return false;
}
if (!allUnique()) {
return false;
}
Finally in isMagic() when you calculate the column's sum, the addition is missing
sumCol = array[j][i];
must be replaced with
sumCol += array[j][i];
Related
This program is attempting to recreate Conway's Game of Life.
The rules that this code is trying to apply:
Empty cells with 3 neighbors come to life
Live cells with <2 or >3 neighbors die
All births / deaths occur simultaneously
The issue is the my code outputs no change among the different iterations, even though there is obviously supposed to be.
Any help or ideas with some of the logic being used in the portion that updates the cells would be greatly appreciated.
I have tried printing out different variables and cells that are filled, but everything (in that regard) seems to be working properly.
Apologizes for not being more in-depth, I am honestly unsure what the error with the code is. Thanks for help in advance.
import java.util.*;
import java.io.*;
public class Game_Of_Life {
public static void main(String[] args) throws IOException {
final int runs = 5;
int organisms;
String[][] real = new String[20][20];
String[][] test = new String[20][20];
Scanner reader = new Scanner(new File("life100.txt"));
for(int i = 0; i < real.length; i++) {
for(int g = 0; g < real.length; g++) {
real[i][g] = test[i][g] = " ";
}
}
while(reader.hasNext()) {
real[reader.nextInt()-1][reader.nextInt()-1] = "*";
test[reader.nextInt()-1][reader.nextInt()-1] = "*";
}
reader.close();
for(int j=0; j<runs; j++) {
for(int i = 0; i < real.length; i++) {
for(int g = 0; g < real.length; g++) {
int neigh = neighbors(real, i, g);
if(test[i][g].equals("*")) {
if(neigh<2 || neigh>3) {
real[i][g] = " ";
}
}
else {
if(neigh == 3) {
real[i][g] = "*";
}
}
}
}
for(int i = 0; i < real.length; i++) {
for(int g = 0; g < real.length; g++) {
real[i][g] = test[i][g];
}
}
System.out.println(" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n");
for(int i = 0; i < real.length; i++) {
System.out.print((i+1) + " ");
for(int g = 0; g < real.length; g++) {
System.out.print(" " + test[i][g] + " ");
}
System.out.println();
}
}
}
public static boolean able(int row, int col, int N) {
if (row >= 0 && col >= 0 && row < N && col < N) {
return true;
}
else {
return false;
}
}
public static int neighbors(String[][] ray, int row, int col) {
int neighbor=0;
int[] rows = {row-1, row-1, row-1, row, row, row+1, row+1, row+1};
int[] cols = {col-1, col, col+1, col-1, col+1, col-1, col, col+1};
for(int i=0; i<8; i++) {
if(able(rows[i], cols[i], 20) && ray[rows[i]][cols[i]].equals("*")) {
neighbor++;
}
}
return neighbor;
}
}
Actual Results: Cells do not become alive or dead after the five iterations I have it running.
Seems to me like all of your checks should be against the "test" array, so change to:
int neigh = neighbors(test, i, g);
Then, once all checks have been made and changes to "real" are done, copy everything from "real" back to "test".
So change:
real[i][g] = test[i][g];
To:
test[i][g] = real[i][g];
I'm trying to figure how answer to these question in my code:
create a method called getValidValues that: returns an array of 9 boolean values that corresponds to 9 digits (1-9) and, it is true if that digit can be placed in that position [row][column] without violating game rules.
This is my code:
public class SudokuClass {
private final int SIZE = 9;
boolean board = new int[SIZE][SIZE];
boolean[][] start = new boolean[SIZE][SIZE];
public SudokuClass() {
for(int i=0; i < SIZE; i++) {
for(int j=0; j < SIZE; j++) {
board[i][j] = 0;
}
}
}
public String toString () {
String result = "";
for (int i = 0; i < SIZE; i++) {
if (i % 3 == 0) {
result = result + "+-------+-------+-------+\n";
}
for (int j = 0; j < SIZE; j++) {
if (j % 3 == 0) {
result = result + "| ";
}
if (scacchiera [i] [j] == 0) {
result = result + " ";
} else {
result = result + board[i][j] + " ";
}
}
result = result + "|\n";
}
result = result + "+-------+-------+-------+\n";
return result;
}
public void addStartValues(int row,int col, int val) {
board[row][col] = value;
start[row][col] = true;
}
public void addMove(int row,int col,int val) {
scacchiera[row][col] = val;
inizio[row][col] = false;
}
public boolean verifyGame () {
if (board.length != 9) {
System.out.println("Board should have 9 rows");
return false;
}
for (int i = 0; i < board.length; i++) {
if (board[i].length != 9) {
System.out.println("Row "+ i +" should have 9 cells.");
return false;
}
}
/* check each cell for conflicts */
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
int cell = board[i][j];
if (cell == 0) {
continue; /* blanks are always OK */
}
if ((cell < 1) || (cell > 9)) {
System.out.println("Row "+ i +", column "+ j +" has value illegal "+ cell);
return false;
}
/* does it match any other value in the same row? */
for (int m = 0; m < board.length; m++) {
if ((j != m) && (cell == board[i][m]))
{
System.out.println("Row "+ i +" has "+ cell +" in position "+ j +" and "+ m);
return false;
}
}
/* does it match any other value it in the same column? */
for (int k = 0; k < board.length; k++) {
if ((i != k) && (cell == board[k][j])) {
System.out.println("Column "+ j +" has "+ cell +" in position "+ i +" and "+ k);
return false;
}
}
/* does it match any other value in the 3x3? */
for (int k = 0; k < 3; k++) {
for (int m = 0; m < 3; m++) {
int testRow = (i / 3 * 3) + k; /* test this row */
int testCol = (j / 3 * 3) + m; /* test this col */
if ((i != testRow) && (j != testCol) && (cell == board[testRow][testCol])) {
System.out.println("Value "+ cella +" at row "+ i +", column "+ j +" matches with value at row "+ testRow +", column "+ testColumn);
return false;
}
}
}
}
}
return true;
}
public int getValoreIn(int row, int col) {
return scacchiera[row][col];
}
private boolean isInRow(int row, int num) {
for (int i = 0; i < SIZE; i++)
if (board[row][i] == num) {
return true;
}
return false;
}
// we check if a possible number is already in a column
private boolean isInCol(int col, int number) {
for (int i = 0; i < SIZE; i++)
if (board[i][col] == number) {
return true;
}
return false;
}
// we check if a possible number is in its 3x3 box
private boolean isInBox(int row, int col, int number) {
int r = row - row % 3;
int c = col - col % 3;
for (int i = r; i < r + 3; i++)
for (int j = c; j < c + 3; j++)
if (board[i][j] == number) {
return true;
}
return false;
}
public boolean[][] getValidValues(int row, int col) {
boolean[][] validValues = new boolean[9][9];
int[] digit = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int i=0; i < digit.length; i++) {
for(int j=0; j < digit.length; j++) {
if(!isInRow(row,digit[i]) && !isInCol(col,digit[i]) && !isInBox(row,col,digit[i])) {
validValues[i][j] = true;
} else {
validValues[i][j] = false;
}
}
}
return validValues;
}
I edited the code, adding other, private, methods called: isInRow, isInCol, isInBox. I thought to do this to get an easier way to implement the method getValidValues. What do you think about? Are there any suggestions?
The main rule in sudoku is: all numbers in a column, a row and a 3x3 square have to be unique. Based on that you have to do three thing:
Iterate over all cells in the same column. If given column contains a number, set that number to invalid.
Same as above but for the row.
Find out the 3x3 square for the cell you're validating. It will start at coordinates like [floor(x/3), floor(y/3)]. Then you iterate over cells in that square and set numbers to invalid, just like above.
I hope that is enough to get you started. Don't want to post the code because that will take away the learning process.
I have coded for Sudoku puzzle in Java. The thing is my code has limitation for giving inputs for 9*9 grid. How do I make my code adaptable for all the grids. Please have patience. I am new to java.
What changes do I need to make so that the code can run on all grid sizes?The grid is square not a rectangle.
class Solution {
public void solveSudoku(char[][] board) {
if(solveSudoku2(board)) {
return;
}
}
public boolean solveSudoku2(char[][] board) {
boolean isEmpty = true;
int row = -1;
int col = -1;
int n = board.length;
//this code is used to check if there exists any empty cell in sudoku board
//if there is any empty cell, that means we are not done yet and we need to solve it further,
// so we cannot return true at any point until all the cells are full
//by empty cell, I mean cells having '.' as the value
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(board[i][j] == '.') {
row = i;
col = j;
isEmpty = false;
break;
}
}
if(!isEmpty) {
break;
}
}
if(isEmpty) {
return true;
}
//loop for all the numbers and start placing in the empty cells
//numbers start from 1 to n
for(int num = 1; num <= n; num++) {
//convert number to char
char char_num = (char)(num + '0');
//check if the number we are adding satisfies all the sudoku rules,
// if it does, then we place that number in the cell
if(checkSafe(board,char_num,row,col)) {
board[row][col] = (char)(num + '0');
//using this number in place row,col, we check for all the other empty places and see if the board is returning true or not
// if the board is not filled that means that we need to use other number in row,col place.
//hence backtrack.
if(solveSudoku2(board)) {
return true;
} else {
board[row][col] = '.';
}
}
}
return false;
}
public boolean checkSafe(char[][] board, char num, int row, int col) {
//checkk if num is present in the row
for(int i = 0; i< board.length; i++ ) {
if(board[row][i] == num) {
return false;
}
}
for(int j = 0; j < board[0].length; j++) {
if(board[j][col] == num) {
return false;
}
}
int checknum = (int)Math.sqrt(board.length);
//check for the current grid. grid will be basically checknum*checknum matrix. where every matrix will start from startrow to startrow + checknum having checknum length.
// so, we we have row = 0, then matrix will start from 0 to 2, i.e. the first 3x3 matrix.
// however, we have row = 2, then also the matrix will start from 0 to 2 - the first 3x3 matrix.
//however, if row = 3, then we will start our matrix from 3 and cotinute upto 5.
int startrow = row - row % checknum;
int startcol = col - col % checknum;
for(int k = startrow; k < startrow + checknum; k++) {
for(int l = startcol; l < startcol + checknum; l++) {
if(board[k][l] == num) {
return false;
}
}
}
return true;
}
}
So i want to create a program that will print true or false depending on the values of the array. If the values in the 2d array (row and column) each equal 15. so the values in the row equal 15 and the values in the column equal 15. My code so far:
public static boolean isAmazingArray(int[][] array) {
int rowTemp = 0;
int colTemp = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
rowTemp += array[row][0];
colTemp += array[0][col];
}
if (rowTemp == 15 && colTemp == 15) {
return true;
}
}
return false;
}
Simple for iteration can do this. Notably, however, this requires that the array is non-jagged (array[i].length == array[0].length for all i in range). If this isn't the case it could still be valid, but the problem becomes a bit more interesting.... fixing...
public static boolean isAmazingArray(int[][] array) {
final int VALID_VAL = 15;
//Check Rows - handle jagged rows without issue
for (int[] row : array) {
int a = 0;
for(int i : row) {a += i;}
if(a != VALID_VAL) return false; //Found a bad row
}
//Check Cols - handle jagged-ness by finding max length row first.
int maxRowLength = 0;
for(int[] i : array){
maxRowLength = Math.max(maxRowLength, i.length);
}
//Init array to hold running sum for each column
int[] colSums = new int[maxRowLength];
for(int r = 0; r < array.length; r++){
for(int c = 0; c < array[r].length; c++){
//Add value to its corresponding column sum
colSums[c] += array[r][c];
}
}
for(int i : colSums){
//Found bad column
if(i != VALID_VAL) return false;
}
//No invalid rows/cols found
return true;
}
Here is my code. I am trying to check for the winner. I am only a beginner, so please make it easy. I wanted the board to change sizes. So, I want the check for winner can get use to the size, it will not just check the 9 blocks.
import java.util.*;
public class TicTacToe {
private String[][] board;
private Scanner console;
public TicTacToe(String[][] table, Scanner console) {
this.board = table;
this.console = console;
}
public void makeTable() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = "_";
}
}
}
public void printTable() {
System.out.print(" ");
for (int i = 0; i < board.length; i++) {
System.out.print(" " + i);
}
System.out.println();
for (int i = 0; i < board.length; i++) {
System.out.print(i + "│");
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + "│");
}
System.out.println();
}
}
public void play(Scanner console) {
int turn = 0;
String player = "_";
makeTable();
printTable();
while (turn != 9) {
int x = console.nextInt();
int y = console.nextInt();
while (x >= board.length || y >= board[1].length) {
System.out.println("Out of bounce, try again!!!");
x = console.nextInt();
y = console.nextInt();
}
while (board[y][x] != "_") {
System.out.println("Occupied, try again!!!");
x = console.nextInt();
y = console.nextInt();
}
if (turn % 2 == 0) {
player = "X";
} else {
player = "O";
}
board[y][x] = player;
turn++;
printTable();
}
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[][] board = new String[3][3];
TicTacToe ttt = new TicTacToe(board, console);
ttt.play(console);
}
}
A winning move can only happen when a piece is placed on the board, so you only need to check winning combinations that involve the piece that was just placed on the board.
For example, if the current state of the board is:
O X O
X X
O
And O places their piece in the middle of the board:
O X O
X O X
O
Then you only need to check the winning combinations that involve this middle piece, namely both diagonals, and the middle column and middle row (4 combinations) out of the total number of winning combinations (8 combinations).
Thus, tracking the last move made is essential to effectively determining if the board is in a winning state.
EDIT
As one person already mentioned, what you're essentially doing is checking to see if the last played move is a winning move. As a result, there really isn't any need to brute force check every row, column, and diagonal systematically to see if there's a winning position or to create some sort of list or table of solutions to check the current board against.
All you really need to do is check the row, column, and diagonal (if the move was on a diagonal) that the move was played on and see if the winning condition is met there.
// Takes the row and column coordinates of the last move made
// and checks to see if that move causes the player to win
public boolean isWinner(int row, int col){
String Player = board[row][col];
int r = row;
int c = col;
boolean onDiagonal = (row == col) || (col == -1 * row + (board.length-1));
boolean HorizontalWin = true, VerticalWin = true;
boolean DiagonalWinOne = true; DiagonalWinTwo = true;
// Check the rows and columns
for(int n = 0; n < board.length; n++){
if(!board[r][n].equals(Player))
HorizontalWin = false;
if(!board[n][c].equals(Player))
VerticalWin = false;
}
// Only check diagonals if the move is on a diagonal
if(onDiagonal){
// Check the diagonals
for(int n = 0; n < board.length; n++){
if(!board[n][n].equals(Player))
DiagonalWinOne = false;
if(!board[n][-1*n+(board.length-1)].equals(Player))
DiagonalWinTwo = false;
}
}
else{
DiagonalWinOne = false;
DiagonalWinTwo = false;
}
boolean hasWon = (HorizontalWin || VerticalWin || DiagonalWinOne || DiagonalWinTwo);
return hasWon;
}
ORIGINAL
A few people have already answered this question, but here's my answer just for the heck of it.
Also, in your play method, you have a while loop to check to make sure that the user doesn't specify a move that is out-of-bounds, but then afterwards you have another while loop check to make sure that the move is in an empty space. You'll still probably want to check to make sure that their new move is also within the boundaries otherwise your loop condition will throw an ArrayOutOfBoundsException.
public boolean isWinner(String player){
// Check for N-in-a-row on the rows and columns
for(int i = 0; i < board.length; i++){
boolean verticalWin = true, horizontalWin = true;
for(int j = 0; j < board.length; j++){
if(!board[i][j].equals(player)))
horizontalWin = false;
if(!board[j][i].equals(player))
verticalWin = false;
if(!(horizontalWin || verticalWin))
break;
}
if(horizontalWin || verticalWin)
return true;
}
// If there was a N-in-a-row on the rows or columns
// the method would have returned by now, so we're
// going to check the diagonals
// Check for N-in-a-row on both the diagonals
boolean diagonalWinOne = true, diagonalWinTwo = true;
for(int n = 0; n < board.length; n++){
diagonalWinOne = true;
diagonalWinTwo = true;
int row = board.length - 1 - n;
if(!board[n][n].equals(player))
diagonalWinOne = false;
if(!board[row][n].equals(player))
diagonalWinTwo = false;
if(!(diagonalOne || diagonalTwo))
break;
}
// If either one of the diagonals has N-in-a-row, then there's a winner
if(diagonalWinOne || diagonalWinTwo)
return true;
// Otherwise, no one has won yet
else
return false;
}
Ok here is how I did it when I made tic-tac-toe. I used Strings
Create a 2D array that contains all the possible winning combinations
Create two String variables, one for each player.
Display the board on the table
Number each of the blocks from 1 to 9 starting at the top left corner
Whenever the either of the user clicks on the board, append the number to the player String
Now, here comes the magic part, checking the winner:
6. For every click on the board, start iterating on the 2d winning combination. Here is how you check if somebody has won:
String[][] winningCombo = ... initialization ...
for( int i = 0 ; i < winningCombo.length; i++){
for(j = 0; j < winningCombo[i].length; j ++){
char c1 = winningCombo[i][j].charAt(0);
char c2 = winningCombo[i][j].charAt(1);
char c3 = winningCombo[i][j].charAt(2);
if(currentPlayerString.contains(c1) && currentPlayerString.contains(c2) && currentPlayerString.contains(c3)){
// currentPlayer has won if he has all the 3 positions of a winning combo
}
}
}
So, if you may consider an alternative approach, you can use that. I used Swing for UI and used GridLayout to layout the various JPanel.
just check rows, cols and both diagonals:
import java.util.Scanner;
public class TTT {
private String[][] board;
private Scanner console;
private int size;
public TTT(String[][] table, Scanner console, int size) {
this.board = table;
this.console = console;
this.size = size;
}
public void makeTable() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = "_";
}
}
}
public void printTable() {
System.out.print(" ");
for (int i = 0; i < board.length; i++) {
System.out.print(" " + i);
}
System.out.println();
for (int i = 0; i < board.length; i++) {
System.out.print(i + "│");
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + "│");
}
System.out.println();
}
}
public void play(Scanner console) {
int turn = 0;
String player = "_";
makeTable();
printTable();
while (turn != 9) {
int x = console.nextInt();
int y = console.nextInt();
while (x >= board.length || y >= board[1].length) {
System.out.println("Out of bounce, try again!!!");
x = console.nextInt();
y = console.nextInt();
}
while (board[y][x] != "_") {
System.out.println("Occupied, try again!!!");
x = console.nextInt();
y = console.nextInt();
}
if (turn % 2 == 0) {
player = "X";
} else {
player = "O";
}
board[y][x] = player;
turn++;
printTable();
if(check()){
System.out.println("Player "+player+" won!");
break;
}
}
}
public boolean check(){
//check diagonals
if(check00ToNN()){
return true;
}
if(check0NToN0()){
return true;
}
for(int i = 0 ; i< size ; i++){
if(checkCol(i)){
return true;
}
if(checkRow(i)){
return true;
}
}
return false;
}
public boolean checkRow(int index){
for(int i = 1 ; i< size ; i++){
if(board[i-1][index]!=board[i][index]||board[i][index]=="_"){
return false;
}
}
return true;
}
public boolean checkCol(int index){
for(int i = 1 ; i< size ; i++){
if(board[index][i-1]!=board[index][i]||board[index][i]=="_"){
return false;
}
}
return true;
}
public boolean check00ToNN(){
for(int i = 1 ; i< size ; i++){
if(board[i-1][i-1]!=board[i][i]||board[i][i]=="_"){
return false;
}
}
return true;
}
public boolean check0NToN0(){ //diagonal
for(int i = 1 ; i< size ; i++){
if(board[i-1][size-i-1]!=board[i][size-i]||board[i][size-i]=="_"){
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int size = 3;
String[][] board = new String[size][size];
TTT ttt = new TTT(board, console,size);
ttt.play(console);
}
}
i just look if there is a winner, since i know who had the last turn, i know who it is.
check() calls the real checkmethods.
i added size since it is scalable.