Ahmed Abdelazim
Ahmed Abdelazim

Reputation: 143

java grid/board for-loop: what row is empty and nearest?

Say I have a program that creates a 4x8 board. Each cell in the board is either a colored object or an emptycell object. How do I find which row in my board is empty and nearest to row 0?

My attempt:

public int emptyRow() {

    int emptyCells = 0;
    int emptyRow;

    for (int i = 0; i < getMaxRows(); i++){
        for (int j = 0; j < getMaxCols(); j++){
            if (getBoardCell(i,j).equals(BoardCell.EMPTY)){
                emptyCells++;

                if (emptyCells == getMaxCols()){
                    return i;
                }
            }
        }
    }

But I realised that this will count all the cells that are empty and I only want 8 empty cells in one row.

Upvotes: 0

Views: 226

Answers (1)

Anthony Tatowicz
Anthony Tatowicz

Reputation: 26

You will first need to create a variable for the inner for loop to count the number of items in that particular row, so you can then determine if it is empty or not. If you start at row 0, then the first row you find will be your closest row. Something like this.

int[][] myBoard = {{1,1,1},{0,0,0},{1,1,1}};

for(int i = 0; i < myBoard.length; i++) {
    int count = 0;
    //Loop through the columns of the row
    for(int j = 0; j < myBoard[i].length; j++) {
        //Check to see if the column for this row is empty if it is add 
        //to our empty cell count
        if(myBoard[i][j] == 0) count ++;
    }

    //If our count is equal to the amount of columns in a row we return 
    //the row index.
    if(count == myBoard[i].length()) return i;
}

Upvotes: 1

Related Questions