Coding Puzzle : Tree Design

Problem:

Write a program that prints a tree made out of ‘*’  and ‘|’ . Shape of the tree depends on the given number N.

Input Format:

Given an integer N.

Output Format:

Display the corresponding tree to standard output.

Note: You can find additional sample input/outputs in the sample testcases download.

Constraints: 1 <= N <= 60

Sample Input

1

Sample Output

   *
  ***
 *****
*******
   |

Sample Input

2

Sample Ouput

      *
     ***
    *****
   *******
    *****
   *******
  *********
 ***********
*************
     |||
     |||

Additional larger testcases can be found in the downloadable zip file->Tree-Design_testcases.

Please consult them to confirm patterns and spacings in the output.

 

Solution Code:

import java.util.Scanner;

public class TreeDesign {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int N = sc.nextInt();
		int height =0;
		int[] rows = new int[N];
		for (int i = 0; i < N; i++) {
			rows[i] = 4 + i;
			height+=rows[i];
		}

		int width = 7;
		for (int i = 1; i < N; i++) {
			if (i % 2 == 0) {
				width = width + (rows[i] - 1) * 2 - 4;
			} else {
				width = width + (rows[i] - 1) * 2 - 2;
			}
		}
		char [][] tree = new char[height + N][width];
		for (int q = 0; q < height+N; q++) {
			for (int p = 0; p < width; p++) {
				tree[q][p]=' ';
			}
		}
		
		int z=0;
		int x = 0;
		for (int t = N - 1; t >= 0; t--) {
			
			for (int i = height - 1-z; i >= height -z- rows[t] ; i--) {

				for (int j = x; j < width - x; j++) {
					tree[i][j] = '*';
				}
				x++;
			}
			if (t % 2 == 0) {
				x = x - 1 - 1-1;
			} else {
				x = x - 1 - 1 ;
			}
			z=z+rows[t];
		}

		int middle = width/2;
		int index = middle -N/2;
		for (int q = height; q < height+N; q++) {
			for (int p = index; p <= middle+N/2; p++) {
				tree[q][p]='|';
			}
		}
		for (int q = 0; q < height+N; q++) {
			System.out.println(new String(tree[q]));
		}
	}
}

One thought on “Coding Puzzle : Tree Design”

Leave a Reply

Your email address will not be published. Required fields are marked *