Matt23

Pyramid Numbers

Mar 16th, 2016
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1.  
  2. public class Main
  3. {
  4.     public static void main(String[] args)
  5.     {
  6.         int n = 4;
  7.         int[][] pyramid = new int[][] {
  8.             {7, 0, 0, 0},
  9.             {5, 6, 0, 0},
  10.             {6, 4, 3, 0},
  11.             {4, 6, 5, 6}
  12.         };
  13.        
  14.         int[][] temp = new int[n][n];
  15.         for (int i = 0; i < n; i++)
  16.             for (int j = 0; j < n; j++)
  17.                 temp[i][j] = 0;
  18.        
  19.         temp[0][0] = pyramid[0][0];
  20.         for (int i = 1; i <= n - 1; i++)
  21.         {
  22.             temp[i][0] = pyramid[i][0] + temp[i - 1][0];
  23.         }
  24.        
  25.         for (int i = 1; i <= n - 1; i++)
  26.         {
  27.             for (int j = 1; j <= n - 1; j++)
  28.             {
  29.                 temp[i][j] = pyramid[i][j] + Math.max(temp[i - 1][j - 1], temp[i - 1][j]);
  30.             }
  31.            
  32.         }
  33.        
  34.        
  35.        
  36.         System.out.println("Pyramid");
  37.         for (int i = 0; i < n; i++)
  38.         {
  39.             for (int j = 0; j < n; j++)
  40.             {
  41.                 System.out.print(pyramid[i][j] + " ");
  42.             }
  43.             System.out.println("");
  44.         }
  45.         System.out.println("");
  46.        
  47.         System.out.println("Temp");
  48.         for (int i = 0; i < n; i++)
  49.         {
  50.             for (int j = 0; j < n; j++)
  51.             {
  52.                 System.out.print(temp[i][j] + " ");
  53.             }
  54.             System.out.println("");
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment