Tuesday, July 3, 2018

How do you print all elements of a matrix in diagonal order?

  1. public class PrintDiagonalMatrix
  2. {
  3.   static final int ROW = 5;
  4.   static final int COL = 4;
  5.   // min of two numbers
  6.   static int min(int a, int b)
  7.   {
  8.     return (a < b) ? a : b;
  9.   }
  10.   // min of three numbers
  11.   static int min(int a, int b, int c)
  12.   {
  13.     return min(min(a, b), c);
  14.   }
  15.   // max of two numbers
  16.   static int max(int a, int b)
  17.   {
  18.     return (a > b) ? a : b;
  19.   }
  20.   // print matrix in diagonal order
  21.   static void diagonalOrder(int matrix[][])
  22.   {
  23.     for (int line = 1; line <= (ROW + COL - 1); line++)
  24.     {
  25.       int start_col = max(0, line - ROW);
  26.       int count = min(line, (COL - start_col), ROW);
  27.       for (int j = 0; j < count; j++)
  28.         System.out.print(matrix[min(ROW, line) - j - 1][start_col + j] + " ");
  29.       System.out.println();
  30.     }
  31.   }
  32.   // print a matrix
  33.   static void printMatrix(int matrix[][])
  34.   {
  35.     for (int i = 0; i < ROW; i++)
  36.     {
  37.       for (int j = 0; j < COL; j++)
  38.         System.out.print(matrix[i][j] + " ");
  39.       System.out.print("\n");
  40.     }
  41.   }
  42.   public static void main(String[] args)
  43.   {
  44.     int M[][] =
  45.     {
  46.         { 1, 2, 3, 4 },
  47.         { 5, 6, 7, 8 },
  48.         { 9, 10, 11, 12 },
  49.         { 13, 14, 15, 16 },
  50.         { 17, 18, 19, 20 }, };
  51.     System.out.print("Given matrix is \n");
  52.     printMatrix(M);
  53.     System.out.print("\nDiagonal printing of matrix is \n");
  54.     diagonalOrder(M);
  55.   }
  56. }
Output:
Given matrix is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

Diagonal printing of matrix is
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20 

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...