Last Updated: 27 Nov, 2020

Play with Pattern

Easy

Problem statement

Ninja wanted to go to a party along with his friends. However, his mom wanted him to go only if he completes a task assigned by her.

She gave Ninja a value and asked him to print an X-shaped pattern.

Example : Pattern for N = 3 (No. of rows = 5, No. of columns = 5) :

1   1
 2 2
  3
 2 2
1   1

Since Ninja is in a hurry and doesn’t want to be late for the party; he asks you to solve the problem. Can you help solve this problem?

Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases. The test cases follow.

The first line of each test case contains a single integer ‘N’.
Output Format:
For each test case, print every row in a new line (row elements not separated by space)

Print the output of each test case in a separate line.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 50
1 <= N <= 1000

Time Limit: 1 sec

Approaches

01 Approach

The idea is to use nested loops in such a way that yields the answer.

 

The steps are as follows:

  • Initially, take a variable ‘value’ equals 1, which will be used to print all the values of the pattern.
  • The pattern consists of precisely N * 2 - 1 rows and columns. Hence we will run an outer loop to iterate through rows with structure from i=0 to i = N * 2 - 1.
    • Since each row contains exactly N * 2 - 1 columns. Therefore, we will run an inner loop from j=0 to j = N * 2 - 1.
      • Since row and column, the count is the same; both loops will run for the same amount of time.
      • Inside this loop, we can notice that numbers are printed for diagonals only, otherwise, we will print space.
      • For the first diagonal, i.e., when row and column number both are equal. It means to print the value whenever i==j.
      • For the second diagonal i.e. values are printed if (i + j) == 2 * (n - 1).
      • For the remaining values, check if i < N-1. If it is then increment the value, else decrement the value.
    • Print a new line after the execution for each row.