Last Updated: 27 Nov, 2020

Ninja and power of 2

Easy
Asked in companies
AmazonRadisys Corporation

Problem statement

Ninja loves playing with numbers. So one day, he wants to arrange a few numbers in the ‘N’ number of rows. The first row contains 1 number, the second row has two numbers, the third row has 4 numbers, and so on.

Ninja starts placing numbers in increasing order, with absolute difference 1, starting from 1 and continuing till he encounters 9, and then he again restarts from 1.

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

Pattern for N = 4:

1
23
4567
89123456
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 'N' lines denoting the required pattern.
Constraints:
1 <= T <= 5
1 <= N <= 15
Where ‘T’ denotes number of test cases and ‘N’ is the given integer denoting the given number of rows.

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 an ‘ans’ matrix to store the final pattern.
  • We initialize a variable ‘k’ to 1, which will be the starting value for the pattern.
  • We will iterate over all the rows, i.e., i = 0 to N - 1:
  • We will run a for loop starting from 0 and less than 2 ^ i.
  • If k is less than 10, we will insert the value in the matrix ‘ans’.
  • Otherwise, we will reset the value of k to 1 and then insert the value in the matrix ‘ans’.
  • We will return the matrix ‘ans’ as the final answer.