Check if 2d array column is full - java

I'm working on a game class project and got stuck.
Ive been looking everywhere on how to check if any column in a 2 dimensional Array is full and if so, the column be completely cleared.
I'm really new to Java so if you can please help me out with this!
This is the code I have so far.
//removes filled columns - added method
private boolean removeFullCol()
{
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[i].length; j++){
if(board[i][j] != occupied){
return false;
}
}
}
//empty square was never found - column is full
return true;
}

If you want to remove only full cols, check by cols, but you cant return a boolean if you want to check ALL columns. You have 2 options:
check a given column (return a boolean)
return first column full (return an int)
First option:
private boolean removeFullCol(int col)
for (int row=0; row<board[col].length; row++) {
// check if all are filled not sure which object is inside board...
if(board[row][col] == null){
return false;
}
}
return true;
}
Second option (returns first col full or data, -1 otherwise):
private int removeFullCol()
for (int row=0; row<board[col].length; row++) {
int filled = 0;
for (int row=0; row<board[col].length; row++) {
// check if all are filled not sure which object is inside board...
if(board[row][col] != null){
filled ++;
}
}
// when finished check how many rows are filled
if (board[col].length == filled)
return row;
}
return -1;
}
I wrote the code on the fly... Let me know if any errors or doubts...

Related

How to traverse through 2d array and count how many elements are greater than 1 in each row in row major order

I'm writing a method that traverses through a 2d array in row-major order and at the start of each row, I initialize a count variable to zero. In the inner loop, if a value is non-zero I increment the count variable. At the end of the row, if the count variable is not exactly equal to 1, return false. Ive been working on this for about 2 weeks and can't find my error. Please point me in the right direction.
** Don't mind the print statements I'm trying to see how much the count is and my code only seems to hit the second row of the array
public static boolean isGPM(int[][] matrix) {
int count =0;
for (int row = 0; row < matrix.length; row++) {
count =0;
for (int col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] > 0) {
count++;
}
else {
return !gpm;
}
}
}
System.out.println(count);
return gpm;
}
If I understand you correctly, you only care about the per-row count. This should work:
int count = 0;
// Process each row...
for (int row = 0; row < matrix.length; row++) {
count = 0;
// Process each column...
for (int col = 0; col < matrix[row].length; col++) {
// Check the cell.
if (matrix[row][col] != 0) {
count++;
}
}
// Row processing complete. Check count.
if (count != 1) {
System.out.println(count);
return gpm;
}
}

Java 2D array diagonals

I wrote a program to try to solve the 8 queens problem and one part of it required me to test all of the forward and backward diagonals to make sure there were no conflicts. I got the backwards to work perfectly but this part of the forward one was returning true while I was testing and I really can't figure out why. And help would be greatly appreciated :)
class NonAttackingQueen {
static char [][] board = { {'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','Q','X','X','X','X','X','X'},
{'Q','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'} };
public static boolean diagonalsClear () {
int numQueens;
boolean clear = true;
for (int numSpots = 1; numSpots < 9; numSpots++) {
numQueens = 0;
for (int row = 0; row < numSpots - 1; row++) {
if (board[row][numSpots - 1 - row] == 'Q')
numQueens++;
}
if (numQueens > 1) {
clear = false;
break;
}
}
for (int numSpots = 7; numSpots > 0; numSpots--) {
numQueens = 0;
for (int row = 7; row > 7 - numSpots; row--) {
if (board[row][15-row-numSpots] == 'Q')
numQueens++;
}
if (numQueens > 1) {
clear = false;
break;
}
return clear;
}
}
Little trick to solve this problem. It is obvious, that you have mistake with matrix row and column indices calculation, and your loops do not cover all cells in it. Easiest way to check it, just print it out to console. I can see, that you have problem with for (int row = 0; row < numSpots - 1; row++). Firs iteration, when numSpots=1 it skips this loop. Correct is for (int row = 0; row <= numSpots - 1; row++).
Let me give you some notes about your example. I can see that two upper and lower part of the matrix you check with opposite direction, upper one you start with row=0 and lower one - col=0. I think to do the same calculation is much better for understanding. You could decomposite you task into three simple once:
Check one single diagonal, starting with given row and column;
check upper diagonals;
check lower diagonals.
I think example below is more clear for reading:
private static boolean isDiagonalClear(int row, int col) {
int total = 0;
do {
if (board[row--][col++] == 'Q')
total++;
} while (total <= 1 && row >= 0 && col < 8);
return total <= 1;
}
public static boolean diagonalsClear() {
for (int row = 0; row < 7; row++)
if (!isDiagonalClear(row, 0))
return false;
for (int col = 0; col < 8; col++)
if (!isDiagonalClear(7, col))
return false;
return true;
}

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.
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;
}

Why won't my array fill with '?'s?

public class MakeQuilt {
public static void main (String[] args){
char [][] myBlock = new char [4][5];
char [][] myQuilt = new char [12][4];
for(int row = 0; row < myBlock.length; row++){
for(int column = 0; column < myBlock[row].length; column++){
if(column == 0 || row == 3)
myBlock[row][column]='X';
else if(row == column || (row == 2 && column == 1))
myBlock[row][column]='+';
else
myBlock[row][column]='.';
}
}
displayPattern(myBlock);
displayPattern(myQuilt);
}
public static void displayPattern(char[][] myBlock){
for(int row = 0; row < myBlock.length; row++){
for(int column = 0; column < myBlock[row].length; column++){
System.out.print(myBlock[row][column]);
}
System.out.println();
}
System.out.println();
}
public static void fillQuilt(char[][] myQuilt){
for(int row = 0; row < myQuilt.length; row++){
for(int column = 0; column < myQuilt[row].length; column++){
myQuilt[row][column] =('?');
}
}
}
}
Can't seem to figure out why my char array myQuilt won't fill with question marks but instead is filled with nothing? (output shows a bunch of 0's). Not sure how to change the displayPattern method to output ?'s in the myQuilt array.
Before calling displayPattern, you have to fill quilt somewhere. i.e.
displayPattern(myBlock);
fillQuilt(myQuilt);
displayPattern(myQuilt);
Question: You define the fillQuilt(...) method where you would fill an array with question mark characters, but where do you ever call this method?
Answer: You don't (at least you don't show it), and if it's never called, it will never do its thing. The solution is to call the fillQuilt method, passing in myQuilt where you need it to do its actions: fillQuilt(myQuilt);. Understand that programming takes things very literally: they only do what you explicitly program them to do, nothing less, nothing more.
I can't see any call to your fillQuilt() method in your main.
Don't you have to call fillQuilt() somewhere before printing?

Java 2d array, test for square

I'm given an array (a2d) and I need to determine if every row and column has the same number of elements as every other row and column. If it is then I set the Boolean isSquare to true.
I have come up with the following code, but it doesn't like it and it isn't giving me any suggestions on how to improve it.
for(int row = 0; row < a2d.length; row++){
for(int col = 0; col < a2d[row].length; col++)
if(a2d.length == a2d[row].length)
isSquare = true;
else
isSquare = false;
}
Am I testing this the wrong way or is there a better way?
There is no need for 2 loops you should be able to do something like this (I'm not going to give the code since it's homework)
1. Save the length of the array (a2d.length)
2. Loop over all the rows
3. Check to see if the given row has the same length
4. if Not return false
5. if you reach the end of the loop return true
for (int i = 0, l = a2d.length; i < l; i++) {
if (a2d[i].length != l) {
return false;
}
}
return true;
You just need to ensure that all of the lengths of the 2nd dimension arrays are the same length as the first dimension array.
if(a2d.length == a2d[row].length)
isSquare = true;
else
isSquare = false;
If the last element passes this will return true always. Try this:
isSquare = true;
for(int row = 0; row < a2d.length; row++){
for(int col = 0; col < a2d[row].length; col++)
if(a2d.length != a2d[row].length)
isSquare = false;
}
Save the length of the array (size.length)
Loop over all the rows
Check to see if the given row has the same length
Set isSquare if true go on otherwise false, to controll the loop
if you reach the end of the loop and isSquare
return true otherwise false
private static boolean isSquare(Object[][] matrix){
boolean isSquare = true;
//Save the length of the array
int size = matrix.length;
//Loop over all the rows and Check to see if the given row has the same length
for (int i = 0; i < size && isSquare; i++) {
isSquare = size == matrix[i].length;
}
return isSquare;
}
or not puristic with fori
private static boolean isSquare(Object[][] matrix){
//Save the length of the array
int size = matrix.length;
//Loop over all the rows and Check to see if the given row has the same length
for (int i = 0; i < size; i++) {
if(size != matrix[i].length)
return false;
}
return true;
}
with enhanced for
private static boolean isSquare(Object[][] matrix){
//Save the length of the array
int size = matrix.length;
//Loop over all the rows and Check to see if the given row has the same length
for (Object[] objects : matrix) {
if (size != objects.length)
return false;
}
return true;
}

Categories

Resources