Pages

Monday, November 20, 2017

Printing Pyramid Without Any Loop In Java

If you are asked to write a java program to print out the following pyramid, I am pretty sure that you will accept the challenge without any doubt.  Wait! Life is not as easy as you think. If  you are given the following restrictions, are you able to solve the problem?:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

a) You can’t use any loop.
b) You can’t use a series of print statements to print the desired output straightly.

Sound interesting!  At this point, you are probably puzzled as I was before.

Solution: I solved this problem with recursion. If you think you are really expert in backtracking, then this problem is a very significant test of your skill.

Tools and Technologies:
a) JDK 1.8
b) Eclipse

My Solution:
public class PyramidWithoutLoop {

 private final int LIMIT = 9;

 private void drawPyramid(int row, int current, int half) {

  System.out.print(current + " ");

  if (row == current) {
   
   System.out.println("");
   
   if (half == 2 && row == 1) {
    return;
   }
   if (half == 2 && row > 1) {
    drawPyramid(row - 1, 1, half);
   }
   if (half == 1 && LIMIT == row) {
    drawPyramid(row - 1, 1, half + 1);
   }
   if (half == 1 && row < LIMIT) {
    drawPyramid(row + 1, 1, half);
   }
  } else {
   drawPyramid(row, current + 1, half);
  }
 }

 public static void main(String[] args) {
  new PyramidWithoutLoop().drawPyramid(1, 1, 1);
 }
}

You can download the code from here as well.

No comments:

Post a Comment