Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyramid of numbers in Java

I am trying to print a pyramid in Java that looks something like this:

                9
              8 9 8
            7 8 9 8 7
          6 7 8 9 8 7 6
        5 6 7 8 9 8 7 6 5
      4 5 6 7 8 9 8 7 6 5 4
    3 4 5 6 7 8 9 8 7 6 5 4 3
  2 3 4 5 6 7 8 9 8 7 6 5 4 3 2
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1

I was looking for ways to solve this on the internet and I stumbled across this :

class Pyramid {
    public static void main(String[] args) {
        int x = 7;
        for (int i = 1; i <= x; i++) {
            for (int j = 1; j <= x - i; j++)
                System.out.print("   ");
            for (int k = i; k >= 1; k--)
                System.out.print((k >= 10) ? +k : "  " + k);
            for (int k = 2; k <= i; k++)
                System.out.print((k >= 10) ? +k : "  " + k);
            System.out.println();
        }
    }
}

Could anyone please help me understand this? Here' what I've figured out :- The outer loop increments till 7 at the same time the inner j loop increments upto x - i which is 6 for the first iteration of the outer loop , then 5 ...and so on .. So basically the left side of the pyramid is just an inverted triangle of blank spaces.

I am having trouble figuring out what is happening in the other two nested loops and the the strange looking if - else parts inside the print statements.

like image 272
Ajit Avatar asked Sep 04 '12 14:09

Ajit


4 Answers

As the task look really complicated in reality is easy. It might look hard at the beginning. Because you thinking about final result not about the route that guide to the result.

To change that we can use old rule of coding, divide and conquer. This approach teach us, to find similarities in complex problem that can be reduce the main problem to simple task that we are capable to perform. In other words we chunk our big problem in few smaller, that can be solved really easy and at the end we combine the small results to a big one.

So lest start with your problem.

Q1: How to print a pyramid of number ?

As we do not know that, lets focus on something else.

To improve our observation we can add some background details

  1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
0 _ _ _ _ _ _ _ _ 9 _ _ _ _ _ _ _ _
1 _ _ _ _ _ _ _ 8 9 8 _ _ _ _ _ _ _
2 _ _ _ _ _ _ 7 8 9 8 7 _ _ _ _ _ _
3 _ _ _ _ _ 6 7 8 9 8 7 6 _ _ _ _ _
4 _ _ _ _ 5 6 7 8 9 8 7 6 5 _ _ _ _
5 _ _ _ 4 5 6 7 8 9 8 7 6 5 4 _ _ _
6 _ _ 3 4 5 6 7 8 9 8 7 6 5 4 3 _ _
7 _ 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 _
8 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1

Now is the time for observation.

From that observation we can came up with following ideas.

Idea: A pyramid is a construction of two triangles.

Conclusion: It is easier to write a half of that pyramid. So lets rephrase sour problem.

Q2: How to write a sequence number that look like triangle ?

This is really simply, we just need two loop for that first loop will be responsible for columns another for rows.

for (int column = 1; column <= 9; column++) {
    for (int row = 1; row <= 9; row++) {
        // Observe what will happen if
        // we use == or <= or > or <>
        if (column ## row) {
            System.out.print(row);
        } else {
            System.out.print(" ");
        }
    }
    System.out.println(' ');
}

When you complete your first task, you will be able to print squares, triangles, lines of numbers on the screen.

So when we know how to print a triangle like this:

   r
c    1 2 3 4 5 6 7 8 9 
   1 _ _ _ _ _ _ _ _ 9 
   2 _ _ _ _ _ _ _ 8 9 
   3 _ _ _ _ _ _ 7 8 9 
   4 _ _ _ _ _ 6 7 8 9 
   5 _ _ _ _ 5 6 7 8 9 
   6 _ _ _ 4 5 6 7 8 9 
   7 _ _ 3 4 5 6 7 8 9 
   8 _ 2 3 4 5 6 7 8 9 
   9 1 2 3 4 5 6 7 8 9 

We should modify your code that would be more suitable, typically operations in computer worlds start from zero not one.

   r
c    0 1 2 3 4 5 6 7 8  
   0 _ _ _ _ _ _ _ _ 9 
   1 _ _ _ _ _ _ _ 8 9 
   2 _ _ _ _ _ _ 7 8 9 
   3 _ _ _ _ _ 6 7 8 9 
   4 _ _ _ _ 5 6 7 8 9 
   5 _ _ _ 4 5 6 7 8 9 
   6 _ _ 3 4 5 6 7 8 9 
   7 _ 2 3 4 5 6 7 8 9 
   8 1 2 3 4 5 6 7 8 9 

When you success with that we stop for the moment and think.

Why do we have to repeat all those operations for each row ? If we could place somewhere the values we do not have to think and calculate them any more only focus on writing the whole result to the screen.

The solution for this problem are arrays and concept of approach known as dynamic programing. In this approach we try to memorize somewhere things that will be used for future operations.

So as a worm up lets just assign the number to and array instead of printing them.

[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [9]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [8] [9]
[ ] [ ] [ ] [ ] [ ] [ ] [7] [8] [9]
[ ] [ ] [ ] [ ] [ ] [6] [7] [8] [9]
[ ] [ ] [ ] [ ] [5] [6] [7] [8] [9]
[ ] [ ] [ ] [4] [5] [6] [7] [8] [9]
[ ] [ ] [3] [4] [5] [6] [7] [8] [9]
[ ] [2] [3] [4] [5] [6] [7] [8] [9]
[1] [2] [3] [4] [5] [6] [7] [8] [9]

At the and you should came up with code like this

int[] array = new int[9];

for (int column = array.length; column > 0; column--) {
    for (int row = 0; row <= array.length; row++) {
        if (column == row) {
            array[row - 1] = column;
        }
    }
    System.out.println(Arrays.toString(array));
}

So what is clear from that code, is that we for each step use set only one value. That is presented below

9  [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [9] - Step one we put nine
8  [ ] [ ] [ ] [ ] [ ] [ ] [ ] [8] [ ] - Step two we put eight
7  [ ] [ ] [ ] [ ] [ ] [ ] [7] [ ] [ ]
6  [ ] [ ] [ ] [ ] [ ] [6] [ ] [ ] [ ]
5  [ ] [ ] [ ] [ ] [5] [ ] [ ] [ ] [ ]
4  [ ] [ ] [ ] [4] [ ] [ ] [ ] [ ] [ ]
3  [ ] [ ] [3] [ ] [ ] [ ] [ ] [ ] [ ]
2  [ ] [2] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
1  [1] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]

After nine steps we will fill whole array with numbers.

What we are still missing is the result on screen. For that we should print our whole array in each step. First we should print it from left to right and after that front end to the beginning.

And the code that do the magic should look like this

public static void pyramide(int levels) {
    int[] tab = new int[levels];
    for (int row = tab.length; row > 0; row--) {
        tab[row - 1] = row;
        //Print left
        for (int i = 0; i < tab.length; i++) {
            if (tab[i] != 0) {
                System.out.print(tab[i]);
            } else {
                System.out.print(' ');
            }
        }
        //Print right
        for (int i = tab.length - 2; i >= row - 1; i--) {
            if (tab[i] != 0) {
                System.out.print(tab[i]);
            }
        }
        System.out.println("");
    }
}
like image 164
Damian Leszczyński - Vash Avatar answered Oct 04 '22 17:10

Damian Leszczyński - Vash


Let's go through this step by step. As you've already figured out, x is a variable representing the height of the pyramid.

then, as you also correctly found out, the first loop creates the indentation of the current line of numbers

the second loop will now write the left half of the numbers, but If I got it right, it will start with the highest number and decrement, and then the third loop will increment the numbers again, creating a slightly different pyramid than the one you're looking for.

now, the strange looking if-else parts, as you're calling them are the the ternary conditional operator, and the only purpose they're fulfilling in this code is fixing the number spacing when the pyramid contains numbers >= 10 by omitting the leading whitespace of the number. :)

like image 32
Andreas Grapentin Avatar answered Oct 04 '22 16:10

Andreas Grapentin


This is homework. You will learn more by doing it yourself, rather than blindly copying someone else's work.

Start with a similar, but simpler problem:

    *
   ***
  *****
 *******

Can you print that triangle? Write your own code, and test that it works correctly.

Now modify your code to print numbers instead of asterisks:

    1
   123
  12345
 1234567

Can you print that triangle? Write your own code, and test that it works correctly.

Now modify your code again to solve the final problem. It is often easier to approach a difficult problem by solving similar, but easier, problems first. By reusing code you can build from a solution to a simple problem to the solution of a more complex one.

By all means incorporate ideas and techniques from the code you have found, but don't just copy it blindly. Write your own code using the good points from their code.

like image 39
rossum Avatar answered Oct 04 '22 16:10

rossum


here we go

public class Pyramid {
    public static void main(String[] args) {
        int[] arry = new int[10];
        for (int i = 1; i <= 9; i++)
            arry[i] = i;
        int index = 0;
        for (int i = 9; i > 0; i--) {
            int loop = 1, tempLoop = 0;

            for (int k = 0; k < 9; k++) {
                if (k < (9 - index))
                    System.out.print(" ");
                else
                    System.out.print(arry[k] + " ");
            }

            for (int k = 9; k >= i && (tempLoop++) <= index; k--) {
                System.out.print(arry[k] + " ");
            }
            index++;
            System.out.println();
        }
    }
}

Output:

         9 
        8 9 8 
       7 8 9 8 7 
      6 7 8 9 8 7 6 
     5 6 7 8 9 8 7 6 5 
    4 5 6 7 8 9 8 7 6 5 4 
   3 4 5 6 7 8 9 8 7 6 5 4 3 
  2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 
 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 
like image 38
twid Avatar answered Oct 04 '22 17:10

twid