Specific cell test understanding the game of life Function - java

I have game of life exercise, I wrote the whole game only remains for me to write the function that checks the cell and decides whether he lives or dies.
the code:
public class lifeGame1 {
public static void main(String[]args){
gameOfLife(4, 5, 0.3);
}
public static void gameOfLife(int n, int m, double p){
int[][] matrix = new int[n][n];
// Random each matrix[i][j]
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(Math.random() < p)
matrix[i][j] = 1;
else
matrix[i][j] = 0;
} // for j
} // for i
System.out.println("The board is: ");
printMatrix(matrix);
int steps = 0;
while(steps < m){
int[][] newMatrix = new int[n][n];
for(int i = 0; i < newMatrix.length; i++){
for(int j = 0; j < newMatrix[i].length; j++){
newMatrix[i][j] = checkTheNewValueOfCell(matrix, i, j);
}
}
matrix = newMatrix;
System.out.println("The new board: ");
printMatrix(matrix);
steps++;
} // while
}
public static void printMatrix(int[][] matrix){
// Random each matrix[i][j]
for(int i = 0; i < matrix.length; i++){ // for each row
for(int j = 0; j < matrix[i].length; j++){ // print one row
System.out.print(matrix[i][j] + " ");
} // for j
System.out.println();
} // for i
}
}
Cell can make the dead or make a life according to the following rules:
1. Live cell can become dead as a result of:
A. If it has a density of more than three live neighbors.
B. Solitude if it has fewer than two live neighbors.
Hence the cell life continues to be my life if and only if it has two or three live neighbors.
2 dead cell can turn the cheek if it has exactly three live neighbors.
While the volume chamber has five neighbors) if Angular three (but also for work the same rules.
Code that checks the cell:
private static int checkTheNewValueOfCell(int[][] matrix, int i, int j) {
// check how much active neighbors
int countActiveNeighbors = 0;
for(int k = i-1; k <= i+1; k++){
for(int m = j-1; m <= j+1; m++){
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום
if(k != i || m != j)
if(matrix[k][m] == 1)
countActiveNeighbors++;
} // if
} // for m
} // for k
if(matrix[i][j] == 1){ // pail
if(countActiveNeighbors == 2 || countActiveNeighbors == 3)
return 1;
else
return 0;
}else{ // savil
if(countActiveNeighbors == 3)
return 1;
else
return 0;
}
}
I was helped by a lecturer who register their function and indeed work, but I did not realize it until the end and it's really important for me to understand it.
I do not understand the loop Four run from i-1 to i + 1 and the loop Four which run from j-1 to j + 1.
If I am in the first cell so I should get an error that the i-1 is equal to -1 and it is beyond the scope of the array does not it?
Can help writing a simple function so we can understand it better?
thank's

You get an ArrayIndexOutOfBoundsException only when you try to ACCESS an non-valid array index. But in the nested for loops, you have the following if statements:
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום
if(k != i || m != j)
if(matrix[k][m] == 1)
countActiveNeighbors++;
} // if
the top if tests that k and m are within the matrix (they are both positive and less than the length/width of the matrix). The bottom if then actually accesses the array at index k,m. Since you check for valid indices before you access, you won't get an Exception

I've commented the function to try and make it clearer. Paired with my comment hopefully it helps you understand!
private static int checkTheNewValueOfCell(int[][] matrix, int i, int j) {
// check how much active neighbors
int countActiveNeighbors = 0; // Neighbor count starts at 0
for(int k = i-1; k <= i+1; k++){ // Loop from 1 before the cell to 1 after the cell
for(int m = j-1; m <= j+1; m++){ // Loop from 1 above the cell to 1 below it
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום // This if statement skips out of bounds in case we are on an edge cell
if(k != i || m != j) // This if statement skips the current cell we are looking at
if(matrix[k][m] == 1)
countActiveNeighbors++; // Finally we increment if we find a neighbor cell
} // if
} // for m
} // for k

Related

Sudoku Generator Algorithm Malfunction

I have a project at school where I have to create a Sudoku Program. I have managed to get a Solver algorithm working but not a Generator. I spent a lot of time online to see if people had found ways to make a working one and I found a man named Mark Fredrick Graves, Jr. (https://www.youtube.com/user/mfgravesjr) who provided a very detailed code on the creation of a sudoku grid on his GitHub (https://github.com/mfgravesjr/finished-projects/tree/master/SudokuGridGenerator). However, I felt that using a one dimensional array was unnecessarily difficult in terms of finding the equations to access lines, columns and boxes. I therefore tried to translate his code into a two dimensional array but I am running into issues with some of his sorting methods and what some variables represent like "int step = (a%2==0? rowOrigin + j: colOrigin + j*9);". What I would like to know is how to translate the methods he uses from one dimensional arrays into two dimensional arrays. Below are the methods (code snippets) in question and my half attempt at translating it myself.
public int[] generateGrid(){
ArrayList<Integer> arr = new ArrayList<Integer>(9);
solvedGrid = new int[81];
for(int i = 1; i <= 9; i++) arr.add(i);
//loads all boxes with numbers 1 through 9
for(int i = 0; i < 81; i++){
if(i%9 == 0) {
Collections.shuffle(arr);
}
int perBox = ((i / 3) % 3) * 9 + ((i % 27) / 9) * 3 + (i / 27) * 27 + (i % 3);
solvedGrid[perBox] = arr.get(i%9);
}
//tracks rows and columns that have been sorted
boolean[] sorted = new boolean[81];
for(int i = 0; i < 9; i++){
boolean backtrack = false;
//0 is row, 1 is column
for(int a = 0; a<2; a++){
//every number 1-9 that is encountered is registered
boolean[] registered = new boolean[10]; //index 0 will intentionally be left empty since there are only number 1-9.
int rowOrigin = i * 9;
int colOrigin = i;
ROW_COL: for(int j = 0; j < 9; j++){
//row/column stepping - making sure numbers are only registered once and marking which cells have been sorted
int step = (a%2==0? rowOrigin + j: colOrigin + j*9);
int num = solvedGrid[step];
if(!registered[num]) {
registered[num] = true;
}else {
//if duplicate in row/column
//box and adjacent-cell swap (BAS method)
//checks for either unregistered and unsorted candidates in same box,
//or unregistered and sorted candidates in the adjacent cells
for(int y = j; y >= 0; y--){
int scan = (a%2==0? i * 9 + y: i + 9 * y);
if(solvedGrid[scan] == num){
//box stepping
for(int z = (a%2==0? (i%3 + 1) * 3: 0); z < 9; z++){
if(a%2 == 1 && z%3 <= i%3) {
continue;
}
int boxOrigin = ((scan % 9) / 3) * 3 + (scan / 27) * 27;
int boxStep = boxOrigin + (z / 3) * 9 + (z % 3);
int boxNum = solvedGrid[boxStep];
if((!sorted[scan] && !sorted[boxStep] && !registered[boxNum]) || (sorted[scan] && !registered[boxNum] && (a%2==0? boxStep%9==scan%9: boxStep/9==scan/9))){
solvedGrid[scan] = boxNum;
solvedGrid[boxStep] = num;
registered[boxNum] = true;
continue ROW_COL;
}else if(z == 8) {
//if z == 8, then break statement not reached: no candidates available
//Preferred adjacent swap (PAS)
//Swaps x for y (preference on unregistered numbers), finds occurence of y
//and swaps with z, etc. until an unregistered number has been found
int searchingNo = num;
//noting the location for the blindSwaps to prevent infinite loops.
boolean[] blindSwapIndex = new boolean[81];
//loop of size 18 to prevent infinite loops as well. Max of 18 swaps are possible.
//at the end of this loop, if continue or break statements are not reached, then
//fail-safe is executed called Advance and Backtrack Sort (ABS) which allows the
//algorithm to continue sorting the next row and column before coming back.
//Somehow, this fail-safe ensures success.
for(int q = 0; q < 18; q++){
SWAP: for(int b = 0; b <= j; b++){
int pacing = (a%2==0? rowOrigin+b: colOrigin+b*9);
if(solvedGrid[pacing] == searchingNo){
int adjacentCell = -1;
int adjacentNo = -1;
int decrement = (a%2==0? 9: 1);
for(int c = 1; c < 3 - (i % 3); c++){
adjacentCell = pacing + (a%2==0? (c + 1)*9: c + 1);
//this creates the preference for swapping with unregistered numbers
if((a%2==0 && adjacentCell >= 81)
|| (a%2==1 && adjacentCell % 9 == 0)) {
adjacentCell -= decrement;
}else {
adjacentNo = solvedGrid[adjacentCell];
if(i%3!=0
|| c!=1
|| blindSwapIndex[adjacentCell]
|| registered[adjacentNo]) {
adjacentCell -= decrement;
}
}
adjacentNo = solvedGrid[adjacentCell];
//as long as it hasn't been swapped before, swap it
if(!blindSwapIndex[adjacentCell]){
blindSwapIndex[adjacentCell] = true;
solvedGrid[pacing] = adjacentNo;
solvedGrid[adjacentCell] = searchingNo;
searchingNo = adjacentNo;
if(!registered[adjacentNo]){
registered[adjacentNo] = true;
continue ROW_COL;
}
break SWAP;
}
}
}
}
}
//begin Advance and Backtrack Sort (ABS)
backtrack = true;
break ROW_COL;
}
}
}
}
}
}
if(a%2==0) {
for(int j = 0; j < 9; j++) {
sorted[i*9+j] = true; //setting row as sorted
}
}else if(!backtrack) {
for(int j = 0; j < 9; j++) {
sorted[i+j*9] = true; //setting column as sorted
}
}else {//reseting sorted cells through to the last iteration
//backtrack = false;
for(int j = 0; j < 9; j++) {
sorted[i*9+j] = false;
}
for(int j = 0; j < 9; j++) {
sorted[(i-1)*9+j] = false;
}
for(int j = 0; j < 9; j++) {
sorted[i-1+j*9] = false;
}
for(int j = 0; j < 81; j++) {
sorted[j] = false;
}
i-=2;
}
}
}
if(!isPerfect(solvedGrid)) {
throw new RuntimeException("ERROR: Imperfect grid generated.");
}
return solvedGrid;
}
My code (unfinished)
public int[][] generateGrid(){
ArrayList<Integer> arr = new ArrayList<Integer>(9);
ArrayList<Integer> values = new ArrayList<Integer>(9);
solvedGrid = new int[9][9];
for(int i = 1 ; i <= 9; i++) {
arr.add(i);
values.add(i);
}
//Fill all boxes with number 1 to 9
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(j == 0) {
Collections.shuffle(arr);
}
solvedGrid[(i/3)*3+(j/3)][(i%3)*3+(j%3)] = arr.get(j);
}
}
//boolean[][] sorted = new boolean[9][9];
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
int[] rowColValues = new int[9];
rowColValues[j] = solvedGrid[0][j];
ArrayList<Integer> occurence = new ArrayList<Integer>();
for(int k = 0; k < rowColValues.length; k++) {
occurence.add((k+1), occurence.get(k+1)+1);
if(occurence.get(k+1) != 1) {
//swap with number in the box that isn't already in rowColValues
//Not sure how to do this...
//Create a method that takes the correct variables as parameters ?
break;
}
}
//Read the sudoku row then column wise and swap values that already exist in the column or row.
}
}
print2DGrid(solvedGrid);
return solvedGrid;
}

How can we generate all submatrix of a given 2D matrix in java or C++?

I am using this loop structure but it fails to generate all the submatrix that are possible for any given 2D matrix with n rows and m columns.
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
System.out.println("sub-MATRIX:");
for(k=i;k<n;k++)
{
for(p=j;p<m;p++)
{
System.out.print(arr[k][p]+" ");
}
System.out.println();
}
}
}
Ex: Given matrix 3X3 : [[1 2 3],[4 5 6],[7 8 9]]
Then its submatrix will be:
for size 1:
[1],[2],[3],[4],[5],[6],[7],[8],[9]
for size 4:
[[1,2],[4,5]],[[2,3],[5,6]],[[4,5],[7,8]] and [[5,6],[8,9]]
and so on
You are missing a couple more loops to cover all cases. PrintMatyrix() should have 2 nested loops for printing contents.
for (i = 1; i < n; ++i)
{
for (j = 1; j < m; ++j)
{
// we are at each sub matrix of size(i,j)
for (k = 0; k <= (n - i); ++k)
{
for (p = 0; p <= (m - j); ++p)
{
// we are at submatrix of size(i,j) starting at (k,p)
// assuming PrintMatrix(Matrix&, int rows, int cols, int r0, int c0);
PrintMatrix(arr, i, j, k, p);
}
}
}
}
If we have a matrix with dimensions M x N, and the sub matrix we are looking for is with K x L dimensions. If there is more optimized solution, please share.
for (int i = 0; i < m-k+1; i++) {
for (int j = 0; j < n-l+1; j++) {
for (int p = 0; p < k; p++) {
for(int q = 0; q < l; q++) {
System.out.print(arr[i+p][j+q] + " ");
}
System.out.println();
}
System.out.println("*****************");
}
}
You should not loops, you should use some recursions.
Think about this way, for each row or column, you either take it or throw away it. So you can select rows first and then columns and based on the rows and columns selected you construct the submatrix.
Some code,
bool rowTaken[N], columnTaken[M];
void constructSubMatrixRow(int i)
{
if (i >= N) constructSubMatrixCol(0);
rowTaken[i] = true;
constructSubMatrix(i+1);
rowTaken[i] = false;
constructSubMatrix(i+1);
}
void constructSubMatrixCol(int i)
{
if (i >= M) printSubMatrix();
columnTaken[i] = true;
constructSubMatrixCol(i+1);
columnTaken[i] = false;
constructSubMatrixCol(i+1);
}
void printSubMatrix()
{
for (unsigned i = 0; i < N; i++)
if (rowTaken[i]){
for (unsigned j = 0; j < M; j++)
if (columnTaken[j])
print matrix[i][j]
}
}

Traversing 2D array and showing the path taken

I am trying to traverse a 2D array, first printing out a random array of 0s and 1s and then looping through that same array to change the 0s to 2s showing the path that is being taken to get from the top to the bottom. It compiles, but I can't quite figure out to get it to change the variables without forgetting about the random array. I tried using another set of for loops, which probably isn't the right way to do it...
Here is what I have come up with.
import java.util.*;
public class SearchMaze{
//Variables to set the values of the 2 arrays
private static int n = 8;
private static int m = 7;
private static int[][] maze = new int[n][m];
private static int i = 0;
private static int j = 0;
public static void main(String [] args){
//Randomly select 0s and 1s for the array
Random rand = new Random();
System.out.print(n + "\t" + m);
System.out.println("");
//creates the random array of 0s and 1s
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
maze[i][j] = rand.nextInt(2);
System.out.print(maze[i][j]);
}System.out.println("");
}
//here I was trying to loop through the array again while changing the 0s to 1s
//to show if a "path" from the top to the bottom exists
//but in doing this I am really just creating a different array of random 0s and 1s..
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
maze[i][j] = rand.nextInt(2);
while(i < n - 1 && j < m - 1){
if(maze[i+1][j] == 0)
{
maze[i+1][j] = 2;
i++;
}
else if(maze[i-1][j] == 0)
{
maze[i-1][j] = 2;
i++;
}
else if(maze[i][j+1] == 0)
{
maze[i][j+1] = 2;
j++;
}
else if(maze[i][j-1] == 0)
{
maze[i][j-1] = 2;
j++;
}
else
{
maze[i][j] = 1;
}
System.out.print(maze[i][j]);
}System.out.println();
}//end second for loop
}//end first for loop
}//end main method
}//end searchmaze
It will either change a few of the numbers at the bottom to 2s, just throw an error or generate an enormous amount of 1s without stopping.
Some of the errors I have come across...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at SearchMaze.main(SearchMaze.java:52)
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1
at SearchMaze.main(SearchMaze.java:42)
I think this is what you need.
import java.util.*;
public class SearchMaze{
//Variables to set the values of the 2 arrays
private static int n = 8;
private static int m = 7;
private static int[][] maze = new int[n][m];
private static int i = 0;
private static int j = 0;
/*
* This function is used for searching a way from top to bottom exist or not.
*/
public static boolean searchMaze(int maze[][], int i, int j, int n, int m) {
if(i == n-1 && j > 0 && j < m && maze[i][j] == 0) {
// This is the condition when there is a way to the bottom.
return true;
} else if(i < 0 || i > m-1 || j < 0 || j > m-1 || maze[i][j] == 1) {
// This is the condition when path is end in some where in middle.
return false;
} else {
// There is three way to go bottom
return searchMaze(maze, i+1, j-1, n, m) || searchMaze(maze, i+1, j, n, m) || searchMaze(maze, i+1, j+1, n, m);
}
}
public static void main(String [] args){
//Randomly select 0s and 1s for the array
Random rand = new Random();
System.out.print(n + "\t" + m);
System.out.println("");
//creates the random array of 0s and 1s
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
maze[i][j] = rand.nextInt(2);
System.out.print(maze[i][j]);
}
System.out.println("");
}
//here I was trying to loop through the array again while changing the 0s to 1s
//to show if a "path" from the top to the bottom exists
//but in doing this I am really just creating a different array of random 0s and 1s..
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
// This is used to search a path from i,j to the bottom.
if(searchMaze(maze, i, j, n, m)) {
System.out.println("There is a way from "+i+" & "+j);
}
}//end second for loop
}//end first for loop
}//end main method
}//end searchmaze

Infinite loop when printing an N x N table

Consider the following Java program:
public class RelativelyPrime {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // Dimensions of grid
int i, j;
int r; // Remainder when i is divided by j
for (i = 1; i <= N; i++) {
for (j = 1; j <= N; j++) {
do { // Using Euclidean algorithm
r = i % j;
i = j;
j = r;
} while (r > 0);
if (i == 1) System.out.print("*");
else System.out.print(" ");
}
System.out.println();
}
}
}
This program prints an N x N table (or matrix, if you like) where N is a command-line argument.
The (i, j)-entry is a * if i and j are relatively prime, or a single whitespace if they are not relatively prime. When I run the program by entering, for instance, java RelativelyPrime 3 it endlessly prints *. Why is this happening?
You changed i and j in the while loop.
for (i = 1; i <= N; i++) {
for (j = 1; j <= N; j++) {
int ii = i, jj = j;
do { // Using Euclidean algorithm
r = ii % jj;
ii = jj;
jj = r;
} while (r > 0);
if (ii == 1) System.out.print("*");
else System.out.print(" ");
}
System.out.println();
}
This is where using the debugger would have helped you solve the problem.
Inside your loops, you alter both i and j which means they never reach N and thus you have an infinite loop.
I suggest you not alter these variables but instead use two new variables, ideally with meaningful names.

TicTacToe resizable board, WIN method error

Hi just attempted a TicTacToe project and was stuck about an error. My error has to do with checking for win solutions specifically diagonals.
What I need:
Create nested loop to loop down the array diagonally, then incrementing it so it would scan diagonally under or to the size until eventually scanning the entire array.
What I did:
I tried to make a nested for loop that would loop through the rows and add the to the counter until the end of the row then check if the counter was equal to the inline (amount in a row needed to win). I believe it works for the rows and columns.
Problem:
But for diagonals, I get an array out of bounds exception and I think it's because my a or b is added to i which could be gameBoard[3][4] when speaking of a 3x3 game board.
Attempt to solve:
I attempted a solution which you can see is the oddly placed for loop with j. So that i would only go to j and not go past the array limits.
I'm wondering if the logic behind this would work?
Sorry if the code is messy especially with the added for loops contain j
/*
* Method winner will determine if the symbol (X or O) wins
*
* #param symbol will be either X or O
* #return will return true if the symbol has won from any of the methods
*/
public boolean winner(char symbol) {
int counter = 0;
/* Scan from ROWS for any symbols inline to win */
for (int i = 0; i < gameBoard.length; i++) { // loop through the rows
for (int j = 0; j < gameBoard.length; j++) { // Loop through the columns
if (gameBoard[i][j] == symbol) {
counter++;
}
if (gameBoard[i][j] != symbol) { // If the next one in the row is not equal then reset counter to 0
counter = 0;
}
if (counter == inline) { // Counter will only equal inline if there is amount of inliine in a row
return true;
}
}
}
/* Scan and search for winning conditions in COLUMNS */
for (int i = 0; i < gameBoard.length; i++) { // loop through the rows
for (int j = 0; j < gameBoard.length; j++) { // Loop through the columns
if (gameBoard[j][i] == symbol) {
counter++;
}
if (gameBoard[j][i] != symbol) { // Reset counter to 0 if not equal to symbol
counter = 0;
}
if (counter == inline) { // If counter reached amount of inline then it must have had amount of inline in a row to win
return true;
}
}
}
/* Scan for RIGHT DIAGONALS for winning conditions */
// a shifts the position of diagonal to the right by one
// after diagonally looping through the board
for (int a = 0; a < gameBoard.length; a++) {
// i loops diagonally through the board
for (int j = gameBoard.length; j < 0; j--) {
for (int i = 0; i < j; i++) {
if (gameBoard[i][i + a] == symbol) {
counter++;
}
if (gameBoard[i][i + a] != symbol) {
counter = 0;
}
if (counter == inline) {
return true;
}
}
}
}
// b shifts the position of the diagonal down by one
for (int b = 1; b < gameBoard.length; b++) {
for (int j = gameBoard.length - 1; j < 0; j--)
// i loops diagonally through the board
for (int i = 0; i < j; i++) {
if (gameBoard[i + b][i] == symbol) {
counter++;
}
if (gameBoard[i + b][i] != symbol) {
counter = 0;
}
if (counter == inline) {
return true;
}
}
}
/* Scan for LEFT DIAGONALS for winning conditions */
// a shifts the position of diagonal to the left by one
for (int a = gameBoard.length; a >= 0; a--) {
for (int j = gameBoard.length; j < 0; j--) {
// i loops diagonally through the board
for (int i = 0; i < j; i++) {
if (gameBoard[i][a - i] == symbol) {
counter++;
}
if (gameBoard[i][a - i] != symbol) {
counter = 0;
}
if (counter == inline) {
return true;
}
}
}
}
// b shifts the position of the diagonal down by one
for (int b = 0; b < gameBoard.length; b++) {
for (int j = gameBoard.length - 1; j < 0; j--) {
// i loops diagonally in the left direction of through the board
for (int i = 0; i < j; i++) {
if (gameBoard[i + b][gameBoard.length - i] == symbol) {
counter++;
}
if (gameBoard[i + b][gameBoard.length - i] != symbol) {
counter = 0;
}
if (counter == inline) {
return true;
}
}
}
}
return false; // If it reaches here then no one has won yet and the game is ongoing
}
As far as i see in your code you must get Array Index Out Of Bounds Exception. I assume you try to implement classic tic-tac-toe, so we are dealing with 3x3 matrix. Here is how your game board is indexed:
[0.0] [1.0] [2.0]
[0.1] [1.1] [2.1]
[0.2] [1.2] [2.2]
So this is what happens in your loop with Right Diagonals:
int a increments 0 --> 2
int j decrements 2 --> 0
int i increments 0 --> 2
So your loop goes like this:
[0.0+0] --> i++ [1.1+0] --> i++ [2.2+0] j--
[0.0+0] --> i++ [1.1+0] j--
[0.0+0] a++
[0.0+1] --> i++ [1.1+1] --> i++ [2.2+1] j-- <--Here you get out of Array.
Additionally after checking through main diagonal, you go through [0.0] [1.1] which is not diagonal at all and you already did this in loops for rows. Even shifting through bottom diagonal is not needed ([0.1][1.2]) as you already did this in loops before. So checking through [0.0] [1.1] [2.2] will do work for you.
I believe that this is ineffective way to check for win condition. You can get rid of 3 loops, just by storing position of found element.
Sorry couldn't get the format for the comments so I'll post what I got here
/* Scan for RIGHT DIAGONALS for winning conditions */
int j = gameBoard.length
for (int a = 0; a < gameBoard.length; a++) {
// i loops diagonally through the board
for (int i = 0; i < j; i++) {
if (gameBoard[i][i + a] == symbol) {
counter++;
}
if (gameBoard[i][i + a] != symbol) {
counter = 0;
}
if (counter == inline) {
return true;
}
} j--; // Incrementing after the i for loop.
}
output:
a:0 i:0 j:3
[0.0+0] --> i++ [1.1+0] --> i++ [2.2+0] /*end for loop. i:2 j:3 a: 0 */
j-- a++
[0.0+1] --> i++ [1.1+1] /*end for loop. i:1 j:2 a: 1*/
j-- a++
[0.0+2] /* end for loop. i:0 j: 1 a:2 */
and the array stays in bounds while checking the diagonals. So I think think can work on a larger scale.

Categories