Diagonal loop through two-dimensional array

String[][] b = [a,b,c] [d,e,f] [g,h,i]; public void LoopDiag() for (int i = b.length - 1; i > 0; i--) { String temp = ""; for (int j = 0, x = i; x <= b.length - 1; j++, x++) { temp = temp+b[x][j]; } System.out.println(temp) } for (int i = 0; i <= b.length - 1; i++) { String temp = ""; for (int j = 0, y = i; y <= b.length - 1; j++, y++) { temp = temp+b[j][y]; } System.out.println(temp); } } 

He is currently printing diagonals, i.e. current current:

 g dg aei bf c 

How can I print other diagonals, I require an output:

 a db gec hf i 
+6
source share
11 answers

Initialize the array for testing purposes only:

  int dim = 5; char ch = 'A'; String[][] array = new String[dim][]; for( int i = 0 ; i < dim ; i++ ) { array[i] = new String[dim]; for( int j = 0 ; j < dim ; j++, ch++ ) { array[i][j] = "" + ch; } } 

Output our matrix:

  for( int i = 0 ; i < dim ; i++ ) { for( int j = 0 ; j < dim ; j++, ch++ ) { System.out.print( array[i][j] + " " ); } System.out.println(); } System.out.println( "============================" ); 

Decision

The indices of elements from diagonals have one rule - their sum is constant along one diagonal:

VARIANT 1

Use two loops to extract all diagonals.

The first cycle retrieves the upper half of the diagonals:

  for( int k = 0 ; k < dim ; k++ ) { for( int j = 0 ; j <= k ; j++ ) { int i = k - j; System.out.print( array[i][j] + " " ); } System.out.println(); } 

The second cycle is repeated on the lower half of the diagonals:

  for( int k = dim - 2 ; k >= 0 ; k-- ) { for( int j = 0 ; j <= k ; j++ ) { int i = k - j; System.out.print( array[dim - j - 1][dim - i - 1] + " " ); } System.out.println(); } 

VARIANT 2

Use one loop to extract all the diagonals, but there are additional iterations and one additional check :

  for( int k = 0 ; k < dim * 2 ; k++ ) { for( int j = 0 ; j <= k ; j++ ) { int i = k - j; if( i < dim && j < dim ) { System.out.print( array[i][j] + " " ); } } System.out.println(); } 

Output:

 ABCDEFGHIJKLMNOPQRSTU VWXY ============================ AFBKGCPLHDUQMIEVRNJWS OXTY 
+10
source

Solutions would be much simpler if we divide it into 2 sub-problems:

  • Find out the beginning of each diagonal.
  • Based on the starting diagonal indices, type the diagonal.

     public void printMatrixDiagonals(int[][] matrix) { int c = 0; int count = matrix.length + matrix[0].length -1; int i = 0, j = 0; //There can be at most m + n -1 diagonals to be printed while (c < count) { //Start printing diagonals from i and j printDiagonal(i, j, matrix); if (i < matrix.length -1) { //We increment row index until we reach the max number of rows i++; } else if (j < matrix[0].length - 1) { //We are at maximum index of row; so its time to increment col index //We increment column index until we reach the max number of columns j++; } c++; } } 

Print Chart: Please note that each time we start printing each diagonal, the row index must be decreased and the column index must be increased. Therefore, given the initial indices of each diagonal, we can print the diagonal as follows:

 private void printDiagonal(int i, int j, int[][] m) { while (i >=0 && j< m[0].length ) { System.out.print(m[i][j] + " "); i--; j++; } System.out.println(""); } 
+4
source

Just help yourself, look at the indices you need to go through:

 #1 (0,0) -> a #2 (1,0) (0,1) -> bd #3 (2,0) (1,1) (0,2) -> gec #4 (2,1) (1,2) -> hf #5 (2,2) -> i 

Look at changing indexes at each iteration and create your own algorithm. Not so difficult, so do your homework yourself;)

+3
source

I wrote the following code. The key should display all the diagonals that start from the top, and then move along the diagonals that start from the sides. I included a method that combines two angles to intersect the diagonals northwest - southeast and northeast - southwest and autonomous methods for traversing the corresponding angles.

 public static void main(String[] args){ int[][] m = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; printDiagonals(m, DiagonalDirection.NEtoSW, new DiagonalVisitor() { public void visit(int x, int y, int[][] m) { System.out.println(m[x][y]); } }); } public enum DiagonalDirection{ NWToSE, NEtoSW } private static abstract class DiagonalVisitor{ public abstract void visit(int x, int y, int[][] m); } public static void printDiagonals(int[][] m, DiagonalDirection d, DiagonalVisitor visitor){ int xStart = d==DiagonalDirection.NEtoSW ? 0 : m.length-1; int yStart = 1; while(true){ int xLoop, yLoop; if(xStart>=0 && xStart<m.length){ xLoop = xStart; yLoop = 0; xStart++; }else if(yStart<m[0].length){ xLoop = d==DiagonalDirection.NEtoSW ? m.length-1 : 0; yLoop = yStart; yStart++; }else break; for(;(xLoop<m.length && xLoop>=0)&&yLoop<m[0].length; xLoop=d==DiagonalDirection.NEtoSW ? xLoop-1 : xLoop+1, yLoop++){ visitor.visit(xLoop, yLoop, m); } } } public static void printDiagonalsNEtoSW(int[][] m, DiagonalVisitor visitor){ int xStart = 0; int yStart = 1; while(true){ int xLoop, yLoop; if(xStart<m.length){ xLoop = xStart; yLoop = 0; xStart++; }else if(yStart<m[0].length){ xLoop = m.length-1; yLoop = yStart; yStart++; }else break; for(;xLoop>=0 && yLoop<m[0].length; xLoop--, yLoop++){ visitor.visit(xLoop, yLoop, m); } } } public static void printDiagonalsNWtoSE(int[][] m, DiagonalVisitor visitor){ int xStart = m.length-1; int yStart = 1; while(true){ int xLoop, yLoop; if(xStart>=0){ xLoop = xStart; yLoop = 0; xStart--; }else if(yStart<m[0].length){ xLoop = 0; yLoop = yStart; yStart++; }else break; for(;xLoop<m.length && yLoop<m[0].length; xLoop++, yLoop++){ visitor.visit(xLoop, yLoop, m); } } } 
+3
source

Here is the code:

 public void loopDiag(String [][] b) { boolean isPrinted = false; for (int i = 0 ; i < b.length ; i++) { String temp=""; int x=i; for(int j = 0 ; j < b.length ; j++) { int y = j; while (x >= 0 && y < b.length) { isPrinted = false; temp+=b[x--][y++]; } if(!isPrinted) { System.out.println(temp); isPrinted = true; } } } } 
+1
source

This is a very intuitive way to print a diagonal matrix during a cycle.

generalize the problem as a whole, not two parts, and optimize in terms of the complexity of space.

 package algorithm; public class printDiagonaly { public static void main(String[] args) { int[][] a = new int[][]{{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}}; int lr = 0; int lc = -1; int fr = -1; int fc = 0; int row = a.length - 1; int col = a[0].length - 1; while (lc < col || fc < col || fr < row || lr < row) { if (fr < row) { fr++; } else { fc++; } if (lc < col) { lc++; } else { lr++; } int tfr = fr; int tlr = lr; int tlc = lc; int tfc = fc; while (tfr >= tlr && tfc <= tlc) { System.out.print(a[tfr][tfc] + " "); tfr--; tfc++; } System.out.println("\n"); } } } 
+1
source

This works for non-square arrays. This is easy to understand, but calls min () and max () once diagonally.

 int ndiags = width + height - 1; System.out.println("---"); for (int diag = 0; diag < ndiags; diag++) { int row_stop = Math.max(0, diag - width + 1); int row_start = Math.min(diag, height - 1); for (int row = row_start; row >= row_stop; row--) { // on a given diagonal row + col = constant "diag" // diag labels the diagonal number int col = diag - row; System.out.println(col + "," + row); relax(col, row); } System.out.println("---"); } 

Here's the output for width = 3, height = 3

 --- 0,0 --- 0,1 1,0 --- 0,2 1,1 2,0 --- 1,2 2,1 --- 2,2 --- 

width = 3, height = 2

 --- 0,0 --- 0,1 1,0 --- 1,1 2,0 --- 2,1 --- 

width = 2, height = 3

 --- 0,0 --- 0,1 1,0 --- 0,2 1,1 --- 1,2 --- 
0
source

As Alex said here, you need to look at the indices in the loop. Below I will tell you how I approached this problem.

 Input: abc ----- (0,0) (0,1) (0,2) def ----- (1,0) (1,1) (1,2) ghi ----- (2,0) (2,1) (2,2) Output: a ----- (0,0) bd ----- (0,1) (1,0) ceg ----- (0,2) (1,1) (2,0) fh ----- (1,2) (2,1) i ----- (2,2) public class PrintDiagonal{ public static void printDR(String[][] matrix, int rows, int cols){ for(int c=0; c < cols; c++){ for(int i=0, j=c; i< rows && j>=0;i++,j--){ System.out.print(matrix[i][j] +" "); } System.out.println(); } for(int r =1; r < rows; r++){ for(int i =r, j= cols -1; i<rows && j>=0; i++,j--){ System.out.print(matrix[i][j] + " "); } System.out.println(); } } public static void main(String[] args){ String[][] matrix ={ {"a","b","c"}, {"d","e","f"}, {"g","h","i"} }; int rows = matrix.length; int columns = matrix[0].length; printDR(matrix ,rows, columns); } } 
0
source

Here's how to do it:

 int [][]mat = { {1,2,3}, {4,5,6}, {7,8,9}, }; int N=3; for (int s=0; s<N; s++) { for (int i=s; i>-1; i--) { System.out.print(mat[i][si] + " "); } System.out.println(); } for (int s=1; s<N; s++) { for (int i=N-1; i>=s; i--) { System.out.print(mat[i][s+N-1-i] + " "); } System.out.println(); } 

The first cycle prints the diagonals starting from the first column, the second cycle prints the remaining diagonals (starting from the bottom line).

Output:

 1 4 2 7 5 3 8 6 9 
0
source
  String ar[][]={{"a","b","c"},{"d","e","f"},{"g","h","i"}}; int size1=ar.length-1, size2=ar.length; for(int i=0; i<ar.length; i++) { String a=""; for(int j=0, x=ar.length-1-i; j<ar.length-i; j++, x--) { if((j+x)==size1) a=a+ar[x][j]; } size1--; System.out.println(a); a=""; for(int j=i+1, x=ar.length-1; j<ar.length; j++, x--) { if((j+x)==size2) a=a+ar[x][j]; } System.out.println(a); size2++; } 

OUTPUT

HES high frequency decibel I a

0
source

This is the same as leoflower. I just changed the variable names for a better understanding.

level = indicates the current diagonal level that is being printed. Example: - level = 2 denotes diagonal elements with indices (0,2), (1,1), (2,0)

currDiagRowIndex = indicates the index of the row of the current diagonal printed

currDiagColIndex = indicates the column index of the current diagonal printed

 void printMatrixDiagonal(int matrix[][], int endRowIndex, int endColIndex){ for(int level = 0; level < endColIndex; level++){ for(int currDiagRowIndex = 0, currDiagColIndex = level; currDiagRowIndex < endRowIndex && currDiagColIndex >= 0 ; currDiagRowIndex++, currDiagColIndex--){ System.out.print(matrix[currDiagRowIndex][currDiagColIndex] + " "); } System.out.println(); } for(int level = 1; level < endRowIndex; level++){ for(int currDiagRowIndex = level, currDiagColIndex = endColIndex-1; currDiagRowIndex < endRowIndex && currDiagColIndex >= 0; currDiagRowIndex++, currDiagColIndex--){ System.out.print(matrix[currDiagRowIndex][currDiagColIndex]+ " "); } System.out.println(); } } 

Input:

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 

Output:

 1 2 6 3 7 11 4 8 12 16 5 9 13 17 21 10 14 18 22 15 19 23 20 24 25 
-2
source

Source: https://habr.com/ru/post/959451/


All Articles