Last Updated: 27 Nov, 2020

Starfield

Easy

Problem statement

Ninja loves playing with characters. So one day, he wants to arrange a few characters in the ‘N’ number of rows. The pattern consists of a left triangle a right triangle and a mirror image of the top part below.

You are given an integer ‘N’ denoting the given number of rows. Can you print the pattern Ninja wants to create?

Pattern for N = 3:
*   *
 * *
* * *
 * *
*   *
Input Format:
The first line contains ‘T’, denoting the number of test cases.

Each test case contains a single integer ‘N’, denoting the number of rows.
Output Format:
For each test case, print the 'N' strings denoting the required pattern in the following ‘N’ lines.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10
1 <= N <= 10^3

Time Limit: 1 sec

Approaches

01 Approach

The key here is to traverse all the lines sequentially, and for each line, we print the required character at the given index.


 

The steps are as follows:

  • We define a matrix ‘ans’ to store the final pattern.
  • We will iterate over all the rows, i.e., i = 0 to i = N - 1:
  • We will run a for loop over the columns i.e., from j = 0 to j = 2 * (N - 1):
  • If i is less than j and (i + j) is less than 2 * (N - 1) then continue.
  • If (i + j) is odd then continue.
  • Else store ‘ * ‘ in ‘ans’.
  • We will iterate over all the rows, i.e., i = N - 1 to i = - 1:
  • We will run a for loop over the columns i.e., from j = 0 to j = 2 * (N - 1):
  • If i is less than j and (i + j) is less than 2 * (N - 1) then continue.
  • If (i + j) is odd then continue.
  • Else store ‘ * ‘ in ‘ans’.
  • We will return ‘ans’ as the final answer.