How to traverse diagonally through two dimensional array in Java? - java

I have a m x n matrix mat and I need to return an array of all the elements of the array in a diagonal order.
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
public int[] findDiagonalOrder(int[][] mat){
int rows = mat.length;
int cols = mat[0].length;
int[] result = new int[rows * cols];
for(int i = 0; i <= rows - 1; i++){
for (int j = 0; j <= cols - 1; j++) {
while(i >= 0) {
i = i - 1;
j = j + 1;
from this point I dont know what should I do. Do you have any tips / advices how to continue to solve it myself?
I'm trying to figure out how to solve this problem by myself.
I'm trying to start from the first row and first column and then continue to traverse the array diagonally.

Related

Sequential filling of a jagged array. How does this code work?

I was going through one of the solutions on the jagged array and could not follow a few of the below lines. Can anyone help me in understanding the below-the-line how the count is being utilized here. I do understand basics of Java but not getting a vision why count is exactly used here.
Program to demonstrate 2-D jagged array in Java:
int arr[][] = new int[2][];
// Making the above array Jagged
// First row has 3 columns
arr[0] = new int[3];
// Second row has 2 columns
arr[1] = new int[2];
// Initializing array
int count = 0;//why do we need count
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++; //how this line of code will work
You can add output to this code. The count variable is needed to sequentially fill the array with integers from 0 and so on.
int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
int count = 0;
// iterate through the rows of the array
for (int i = 0; i < arr.length; i++)
// iterate through the columns of the array
for (int j = 0; j < arr[i].length; j++)
// set the array element and increment the counter
arr[i][j] = count++;
// output
for (int[] row : arr) System.out.println(Arrays.toString(row));
Output:
[0, 1, 2]
[3, 4]

Java pascal triangle initialization question

I have this code below as I saw from textbook
public static int[][] Pascal(int N) {
int[][] result = new int[N][]; // Build a grid with specific number of rolls
for (int i = 0; i < N; i += 1) {
result[i] = new int[i + 1]; // Build an empty row with length
result[i][0] = result[i][i] = 1;
for (int j = 1; j < i; j += 1) {
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
}
}
return result;
}
I have no question for how this Pascal triangle is achieved, all very clear.
However, I did learned before that to create an Array, length must be given,
for example, int[] A = int[]; will give me Error
It has to be int[] A = int[N]; or int[] A = int[]{1,2,3,etc.};
So when we create the array grid int[][] result = new int[N][];
How is it allow me to only specify the number of rows, but leave the length of each row with blank?
I did noticed that the length of each roll was defined later at result[i] = new int[i + 1];, I still don't understand why this grid is allowed to be initiated.
Thanks!

How to convert ArrayList to Array 2 dimension in java

I want to convert ArrayList to Array 2-Dimension
I have the code below:
ArrayList<String> arrayList=new ArrayList();
arrayList.add("A")
arrayList.add("B")
arrayList.add("C")
arrayList.add("D")
arrayList.add("E")
arrayList.add("F")
int nSize=0,n3item=0, remain=0;
nSize=arrayList.size();
n3item=nSize/3;
remain=nSize%3;
String[][] array[n3item][3]
I want to convert ArrayList to array for example
array[0][1]="A"
array[0][2]="B"
array[0][3]="C"
array[1][1]="D"
array[1][2]="E"
array[1][3]="F"
Now I haven't a solution to do this.
In case of remain is not 0. How to give a solution to this problem
I need your help.
Thanks.
You can use a simple nested for-loop to achieve this.
int numCol = 3;
int numRow = (int) Math.ceil(arrayList.size() / ((double) numCol));
String[][] array = new String[numRow][numCol];
int i, j;
for (i = 0; i < numRow; i++) {
for (j = 0; j < 3 && (i * numCol + j) < arrayList.size(); j++) {
array[i][j] = arrayList.get((i * numCol) + j);
}
}
numRow is found by taking the ceil of number of elements in the list divided by num of desired columns.
eg - when arraylist has 7 elements, numRow will be ceil(7/3.0) = 3.
The main trick here is in the inner for-loop condition (i * numCol + j) < arrayList.size(). It enables us to terminate the loop for the condition remain != 0 you mentioned.
Try to think, how you can fill the 2D array with arraylist values. You need to use a nested loop for assigning the values into the 2D array. Outer loop will iterate over the rows and inner loop will fill the values into each 1D array.
int index = 0;
for(int i = 0; i < n3item; i++) {
for(int j = 0; j < 3; j++) {
array[i][j] = arrayList.get(index);
index++;
}
}

Parsing large numbers into binary

I am trying to make a program that finds the maximum possible determinant of an n*n binary [0,1] matrix. The problem with my current code is that after 4x4, the numbers are too long for a 'long' to hold. The code below is what I use to generate the matrices.
for (int j = 0; j < Math.pow(2, Math.pow(dim, 2)); j++) { //for each possible matrix
int[][] matrix = new int[dim][dim];//make a 2d i*i matrix
long t = Long.valueOf(Long.toBinaryString(j)); //line 58
//format the string so its length = # of elements in the matrix
String format = "%0" + (dim * dim) + "d";
String s = String.format(format, t);
//fill matrix
int counter = 0;
for (int k = 0; k < dim; k++) {//for each row
for (int l = 0; l < dim; l++) {//for each column
matrix[k][l] = s.charAt(counter) - 48; //the -48 is for ascii conversions
counter++;
}// end l
}// end k -- matrix is filled
The error I get when I go over a 4*4:
Exception in thread "main" java.lang.NumberFormatException: For input string: "10000000000000000000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:444)
at java.lang.Long.valueOf(Long.java:540)
at determinants.Determinants.findMaxBinDet(Determinants.java:58)
at determinants.Determinants.main(Determinants.java:38)
What else can I do to parse the number into binary?
It appears you want to create with all the combinations of 0 and 1 in the cells. A much simpler approach is
for (long j = 0, limit = 1<<(dim*dim); j < limit; j++) { //for each possible matrix
int[][] matrix = new int[dim][dim];//make a 2d i*i matrix
//fill matrix
for (int k = 0, counter = 0; k < dim; k++) {//for each row
for (int l = 0; l < dim; l++, counter++) {//for each column
matrix[k][l] = (j >>> counter) & 1;
}
}
This will only work up to 7x7 matrixes but since generating all 8x8 combination is like to take more than a lifetime, you need another approach for that.

Raising a matrix to the power method JAVA

I am having a really hard time creating a method to raise a matrix to the power. I tried using this
public static int powerMethod(int matrix, int power) {
int temp = matrix ;
for (int i = power; i == 1; i--)
temp = temp * matrix ;
return temp ;
but the return is WAYYY off. Only the first (1,1) matrix element is on point.
I tried using that method in a main like so
// Multiplying matrices
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
for (l = 0; l < row; l++)
{
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
// Solving Power of matrix
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
Where "power", "row", and "column" is an int that the user enters.
Any ideas how I can do this??
Thanks!!!
You have a lot of issues here.
First, your matrix squaring algorithm has a (common) error. You have:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
for (l = 0; l < row; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
However, you need to store the result in a temporary second matrix, because when you do matrix[i][j] = sum, it replaces the value at that position with the output, then later results end up being incorrect. Also I suggest initializing sum to 0 first, since it appears you declare it outside of this loop, and initializing it first protects you against any arbitrary value sum may have before going into the loop. Furthermore, it is not immediately clear what you mean by row and column -- make sure you are iterating over the entire matrix. E.g.:
int temp[][] = new int[matrix.length];
for (i = 0; i < matrix.length; i++) {
temp[i] = new int[matrix[i].length];
for (j = 0; j < matrix[i].length; j++) {
sum = 0 ;
for (l = 0; l < matrix.length; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
temp[i][j] = sum ;
}
}
// the result is now in 'temp', you could do this if you wanted:
matrix = temp;
Note that matrix.length and matrix[i].length are fairly interchangeable above if the matrix is square (which it must be, in order to be multiplied by itself).
Secondly, your multiplication squares a matrix. This means if you repeatedly apply it, you keep squaring the matrix every time, which means you will only be able to compute powers that are themselves powers of two.
Your third issue is your final bit doesn't make much sense:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
It's not immediately clear what you are trying to do here. The final part seems to be trying to raise individual elements to a certain power. But this is not the same as raising a matrix to a power.
What you need to do is define a proper matrix multiplication method that can multiply two arbitrary matrices, e.g.:
int[][] multiplyMatrices (int[][] a, int[][] b) {
// compute and return a x b, similar to your existing multiplication
// algorithm, and of course taking into account the comments about
// the 'temp' output matrix above
}
Then computing a power becomes straightforward:
int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; ++ n)
result = multiplyMatrices(result, a);
return result;
}
Why not just use Math.pow?
import java.lang.Math;
Then you just have to do
matrixFinal[power][i][j] = (int) Math.pow(matrix[i][j],power); //might have to cast this to an int

Categories

Resources