Fabian van Rooyen - 1 year ago 90
Java Question

# Check array on 4 in a row

I have this array which i want to check on 4 in a row (the game). I can do it with hundreds of if else but how can I do it in a loop? Is this even possible?
This is my code. Thanks in advance!

``````int array[][] = {{0, 1, 1, 1, 1, 0, 0},
{0, 0, 0, 1, 0, 1, 1},
{0, 0, 0, 1, 0, 1, 1},
{0, 1, 1, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 1, 1},
{1, 0, 0, 1, 0, 1, 0}};

for (int rows = 0; rows < 6; rows++) {
for(int columns = 0; columns < 7; columns++) {
System.out.print(array[rows][columns] + " ");
}
System.out.println();
}

if (array[0][0] == 0) {
if(array[0][1] == 0) {
if (array[0][2] == 0) {
if (array[0][3] == 0) {
System.out.println("Connect Four!");
}
}
}
}
``````

I would introduce a counter and increase it every time a 0 is in your current "line" and reset it if the current number is a 1. If the counter reaches 4, you have 4 connected.

Take a look at this:

``````int array[][] = {{0, 1, 1, 1, 1, 0, 0},
{0, 0, 0, 1, 0, 1, 1},
{0, 0, 0, 1, 0, 1, 1},
{0, 1, 1, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 1, 1},
{1, 0, 0, 1, 0, 1, 0}};

//Search rows
for (int i = 0; i < array.length; i++) {
int rowCount = 0;
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] == 0) {
rowCount++;
} else {
rowCount = 0;
}
if (rowCount == 4) {
System.out.println("yay");
}
}
}
``````

This is not the complete code, only for rows. But it should give you an idea on how to solve your problem for rows and even diagonals, too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download