Okay, So I have this method I made that searches a 2d array of user input column length and row length comprised of integers. The method is suppose to find 4 alike numbers in rows, columns, and both major and minor diagonals throughout the entire array. The array can be as large as the user would like. My method works, however it is extremely ugly and feels redundant. I feel like there should be a better way to compact my code that I just am not seeing. Can anyone tell me how I may accomplish this? I am trying to self teach myself so I don't really have any help but my own. Please dont bash my ugly code :) haha. My main issue is the check diagonals part... It seems like it could be shorter.
public static boolean isConsecutiveFour(int[][] values) {
int count = 0;
int currentElement = 0;
//count rows
for (int x = 0; x < values.length; x++) {
count = 0;
currentElement = values[x][0];
for (int y = 0; y < values[x].length; y++) {
if (currentElement == values[x][y])
count++;
currentElement = values[x][y];
}
if (count >= 4)
return true;
}
//count columns
for (int x = 0; x < values[0].length; x++) {
count = 0;
currentElement = values[0][x];
for (int y = 0; y < values.length; y++) {
if (currentElement == values[y][x])
count++;
currentElement = values[y][x];
}
if (count >= 4)
return true;
}
//count diagonals
for (int x = 0; x < values.length; x++) {
int increaseRow = x;
for (int y = 0; y < values[x].length; y++) {
int currentMajElement = values[x][y], currentSubElement = values[x][y];
int majCount = 1, subCount = 1;
int increaseColumn = y, decreaseColumn = y;
//Check major diagonals
while (increaseRow < values.length && increaseColumn < values[x].length) {
if (currentMajElement == values[increaseRow][increaseColumn])
majCount++;
currentMajElement = values[increaseRow][increaseColumn];
increaseColumn++;
increaseRow++;
}
increaseRow = x;
//Check minor diagonals
while (increaseRow < values.length && decreaseColumn >= 0) {
if (currentSubElement == values[increaseRow][decreaseColumn])
subCount++;
currentSubElement = values[increaseRow][decreaseColumn];
increaseRow++;
decreaseColumn--;
}
if (majCount >= 4 || subCount >= 4)
return true;
}
}
return false;
}