Last Updated: 27 Nov, 2020

Print the Pattern

Moderate
Asked in companies
Citi BankCIS - Cyber InfrastructureDell Technologies

Problem statement

Ninja is given a pattern. Now he is asked to print the same pattern for any given ‘N’ number of rows.

Note:

There is only one space between the values of each column in a row.

For example, Pattern for ‘N’ = 5 will be.
1 2 3 4 5 
11 12 13 14 15 
21 22 23 24 25 
16 17 18 19 20 
6 7 8 9 10 

Input Format:

The first line contains an integer 'T' which denotes the number of test cases or queries to be run.

The first line of each test case contains a single integer ‘N’ denoting the number of rows for which pattern needs to be printed.

Output Format:

The output of each test case will be 'N' strings denoting the pattern printed for the given ‘N’ number of rows.

The output of each test case will be printed on a separate line.

Constraints:

1 <=T <= 5 
1 <= N <= 100

Where ‘T’ is the total number of test cases and ‘N’ is the given number of rows for which pattern needs to be printed.

Time limit: 1 sec

Approaches

01 Approach

We can observe that there are ‘N’ numbers of rows (where ‘N’ is the total number of rows to be printed). Each row contains a different value in the first column and its value increments by 1 for each subsequent column.

 

Algorithm:

 

  • Declare an array of strings for storing the pattern.
  • Declare a variable ‘startValue’  and initialize its value to 1.
  • Declare a variable ‘row’ for keeping track of the number of rows
  • Run an outer loop from ‘row’ = ‘1 to ‘row’ = ‘N’.
    • Declare an empty string for storing the values in the current row.
    • Run an inner loop for printing values from ‘col’ = ‘startvalue’ to ‘col’= ‘startvalue + N - 1’.
    • For every row, we need to set the value of ‘startvalue‘ according to the following conditions:
      • If ‘row’ == (‘N’ + 1) / 2
        • If ‘N’ % 2 ! = 0
          • Set ‘startValue’ = ‘N’ * (‘N’ - 2) + 1
        • Else
          • Set ‘startValue’ = ‘N’ * (‘N’ - 1) + 1
      • Else If ‘row’ > (‘N’ + 1) / 2
        • Set ‘startValue’ = ‘startValue’ - 2 * ‘N’
      • Else
        • Set ‘startValue’ = ‘startValue’ + 2 * ‘N’
    • After the loop, we append the string to our new row and move to a new row of our array.