How to check if a 2D array is diagonally dominant in Java - java

Hey guys i want to make a function which checks a 2D array whether is diagonallydominant or not
Any Ideas??
I have managed to find the diagonall but how to check if diagonally dominant??
public static int arraySum(int[][] array){
int total = 0;
for (int row = 0; row < array.length; row++)
{
total += array[row][row];
}
return total;
}

According to Wikipedia, a diagonally dominant matrix is a matrix such that:
for every row of the matrix, the magnitude of the diagonal entry in a row is larger than or equal to the sum of the magnitudes of all the other (non-diagonal) entries in that row.
This just checks for weak diagonal dominance, given a 2D array:
public boolean isDiagonallyDominant(int[][] array) {
int otherTotal = 0;
// Loop through every row in the array
for(int row = 0; row < array.length; row++) {
otherTotal = 0;
// Loop through every element in the row
for(int column = 0; column < array[row].length; column++) {
// If this element is NOT on the diagonal
if(column != row) {
// Add it to the running total
otherTotal += Math.abs(array[row][column]);
}
}
// If this diagonal element is LESS than the sum of the other ones...
if(Math.abs(array[row][row]) < otherTotal) {
// then the array isn't diagonally dominant and we can return.
return false;
}
}
return true;
}

In theory: in the i-th row, check that the i-th entry is smaller than the sum of the absolute values of the other values of the row:
public boolean checkDominance(int[][] matrix)
{
for (int i = 0; i < matrix.length; ++i)
{
int diagEl = Math.abs(matrix[i][i]);
int sum = 0;
for (int j = 0; j < matrix[0].lenght; ++j)
{
if (i == j) { continue; }
sum += Math.abs(matrix[i][j]);
}
if (sum > diagEl) { return (false); }
}
return (true);
}

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

Jagged array; check for column-wise value increase

This method is simple, there is 2D array, not a rectangle, the purpose is to check the values in each column whether they are increasing or not, if they are in an increasing order, return true, else return false.
The shape of the array is like the following, it is a Young Tableaux
{
[1,4,5,10,11],
[2,6,8],
[3,9,12],
[7]
}
The main properties of a young tableaux:
it consists of cells which are filled with integers, and arranged in
left-justified rows,
no row is longer than a preceding row,
from left to right in any row, and down any column the integers are increasing,
the set of integers used is {1, 2, . . . , n} where n is the number
of cells
How I solve it?
My approach is simple, first convert this 2D array into a rectangle matrix, if some position is empty, then filled it with 0.
Then check the column one by one, if found a error, then break, and return the result.
It works, I just wonder if there is a better apporach for this.
public static boolean columnValuesIncrease(int[][] t) {
//How many columns are there?
int columnCounts = t[0].length;
int rowCounts = t.length;
//create a rectangle matrix, fill 0 when outIndex
int[][] addZero = new int[rowCounts][columnCounts];
for (int row = 0; row < rowCounts; row++) {
for (int col = 0; col < t[0].length; col++) {
try {
addZero[row][col] = t[row][col];
} catch (IndexOutOfBoundsException e) {
addZero[row][col] = 0;
}
}
}
//Let's check the damn column!
boolean mark = true;
myLoop:
for (int col = 0; col < columnCounts; col++) {
for (int row = 0; row < rowCounts; row++) {
if (row + 1 < rowCounts && col + 1 < columnCounts) {
if (addZero[row + 1][col] != 0) {
mark = addZero[row][col] <
addZero[row + 1][col] ? true : false;
}
}
if (!mark) {
break myLoop;
}
}
}
return mark;
}
This approach takes a row. It considers 'this' row and the one after it. It considers N number of columns, where N is the minimum of the number of columns in this row and the row after. In math, if R is the number of rows in this 2D matrix, take some r1: r1 ∈ [0, R) and r2 = r1 + 1. Then, N = min{num_cols(r1), num_cols(r2)}.
In column n, where n ∈ [0, N], if the value at the column in the next row happens to be smaller than the value in the preceding row, it returns false. If everything else worked, it returns true.
public static boolean columnValuesIncrease(int[][] t) {
for(int i = 0 ; i < t.length - 1 ; i++)
for(int j = 0 ; j < Math.min(t[i].length, t[i+1].length) ; j++)
if(t[i][j] > t[i+1][j])
return false;
return true;
}

Adding Java 2d Arrays

I need to create a method within my class to add two 2d arrays together. One is implemented as a parameter in the method, while the other is a class object. I need to make sure the arrays are the same size, and if so, add them together. I keep getting an Array Out of Bounds error. Whats wrong with my code?
// method to add matrices
public int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
if (userArray[row][column] == matrix[row][column]) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
if (userArray[row][column] == matrix[row][column]) is the problem.
Remember that arrays are zero-indexed so the elements are numbered from zero to row - 1. Trying to access row row is guaranteed to throw an ArrayIndexOutOfBoundsException because the last row is at index row - 1.
I'm not sure why you even have this line. If you change row to row - 1 and column to column - 1 then this line checks if the bottom-right values in the two matrices are the same. If they're not then the matrices will not be summed. Is that what you intended to do?
I think this is what you are trying to do :
public class Test {
static int row =3;
static int column =2;
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}};
public static void main(String[] args) {
add(new int[][] {{4,4},{5,5},{6,6}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
//check arrays are of the same size
if ((userArray.length == matrix.length) && (userArray[0].length == matrix[0].length) ) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (column -1)) {
for(int col = 0; col < column; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
}
return addedMatrices;
}
}
or better:
public class Test {
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}, {4,4}};
public static void main(String[] args) {
add(new int[][] {{5,5},{6,6},{7,7},{8,8}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
//check arrays are of the same size
if ((userArray.length != matrix.length) || (userArray[0].length != matrix[0].length) ) {
System.out.println("Error: arrays are not of the same size");
return null;
}
int rows = userArray.length;
int cols = userArray[0].length;
int addedMatrices[][] = new int[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (cols -1)) {
for(int col = 0; col < cols; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
return addedMatrices;
}
}
to make the print out more elegant you could change the for loop to :
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
}
System.out.println(Arrays.toString(addedMatrices[i]));
}
The line if (userArray[row][column] == matrix[row][column]) { should be replaced by a line to check if the dimensions of both matrices are the same (I guess that is what's intended). Assuming they are both rectangular arrays, and non empty:
public class MatrixAdder {
static public int[][] userArray = {{1,2},{3,4},{5,6}};
static public int[][] add(int[][] matrix) {
final int nb_rows1 = matrix.length; // nb rows in matrix
final int nb_cols1 = matrix[0].length; // nb columns in matrix
final int nb_rows2 = userArray.length; // nb rows in userArray
final int nb_cols2 = userArray[0].length; // nb columns in userArray
// this assumes A[0] exists, and A[0].length == A[1].length == ...
// both for matrix and userArray
int addedMatrices[][] = new int[nb_rows1][nb_rows1];
if ((nb_rows1==nb_rows2) && (nb_cols1==nb_cols2)) {
for (int i = 0; i < nb_rows1; ++i) {
for (int j = 0; j < nb_cols1; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
static public void main(String[] args)
{
int[][] mx1 = {{10,100},{20,200},{40,400}};
int [][] mx2 = add(mx1);
}
}
To be more robust, you could check that the dimensions of all sub-arrays are the same. You could also check if the matrix has zero dimension (otherwise array[0] will give an error).
If the dimensions are not the same, the returned matrix is filled with zeroes.
If this is not exactly what you need, it should give you enough hints.
if (userArray[row][column] == matrix[row][column]) {}
This is strange to me, I honestly don't know what the intentions are (Your just comparing the last element of each array).
I would do
if(addedMatrices.length == userArray.length && addedMatrices.length == matrix.length){}.
This is ugly but I don't know anything about userArray or matrix. I am presuming userArray is global. Also do j++ and i++, it has the same end result but it is more of the norm.

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

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