Reputation: 589
I have a 2D Array filled with consecutive integers 1-52 as well as four 0's. I have also created a count variable and set it equal to 0; I want to search through the array and for every 0 that immediately follows either 13,26,39, or 52, increment count++
.
int count =0;
for(int i=0;i<4;i++) {
for(int j=0; j<4;j++) {
if((board[i][j]== 13 && board[i][j+1]==0) || (board[i][j]== 26 && board[i][j+1]==0) || (board[i][j]== 39 && board[i][j+1]==0) || (board[i][j]== 52 && board[i][j+1]==0) ) {
count++;
}
}
}
while(count <4) {
move(board);
}
My current code runs properly and will increment count for a single zero following these numbers. However I want to increment count+=2
if one of my four numbers is immediately followed by two 0's (increment +=3
for three 0's and +=4
for four 0's).
Upvotes: 1
Views: 65
Reputation: 415
You can use a boolean to check whether you are on a count 'streak' of zeroes:
int count = 0;
boolean onACountStreak = false;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (board[i][j] == 0) {
// Count only if this zero is found in a streak
if (onACountStreak) {
count++;
}
}
else if (board[i][j] % 13 == 0) {
onACountStreak = true;
}
else {
onACountStreak = false;
}
}
}
while (count < 4) {
move(board);
}
Upvotes: 0
Reputation: 831
Just make another method to count zeros:
int count =0;
for(int i=0;i<4;i++) {
for(int j=0; j<4;j++) {
if((board[i][j]== 13 || board[i][j]== 26 || board[i][j]== 39 || board[i][j]== 52 ) && board[i][j+1]==0 ) {
count += numberOfZeros(i, j);
}
}
}
while(count <4) {
move(board);
}
}
public int numberOfZeros(int i, int j){
int aux = 0;
for(; j<4;j++) {
if(board[i][j] == 0){
aux++;
}
}
return aux;
}
PS: I edited your if clause to make it more clear
Upvotes: 1