Magical Pattern

Posted: 3 Aug, 2020
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You have been given an integer 'N'. Your task is to print the Magical Pattern(see examples) for the given 'N'.

Example :

For 'N' : 4
Pattern :
4 3 2 1 2 3 4                                                                   
3 3 2 1 2 3 3                                                                   
2 2 2 1 2 2 2                                                                   
1 1 1 1 1 1 1                                                                   
2 2 2 1 2 2 2                                                                   
3 3 2 1 2 3 3                                                                   
4 3 2 1 2 3 4
Input Format :
The first input line contains an integer 'T', the number of test cases. Then 'T' test cases follow.

The first and the only line of input contains the integer 'N'.
Output Format :
For each test case print the Magical Pattern as shown in the example. 
Note :
You don't need to print anything. It has already been taken care of, just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 10^2

Time Limit : 1 sec
Approach 1

Think of all elements as having coordinates. The element in the center row and center column will have coordinates (0, 0). We will refer to it as the origin. The first coordinate measures the horizontal distance from the origin and the second one measures the vertical distance. The right and down directions are positive directions and consequently, the up and left directions are negative directions. So, the element just to the right of the origin will have coordinates (1, 0) and the element just above the origin will have coordinates (0, -1). 

 

Now, we can figure out that the coordinates of the elements at the top left, top right, bottom left and bottom right are (-(N - 1), -(N - 1)), (-(N - 1), (N - 1)), ((N - 1), -(N - 1)) and ((N - 1), (N - 1)) respectively.

 

Now that we got the coordinates for each element to be printed, we can start to look for the relationship between an element's value and its coordinates.

 

We can notice that if the coordinates of an element are (i, j) then its value is min(abs(i), abs(j)) + 1. So to print them, we can run two nested loops: both from -(N - 1) to (N - 1).

Try Problem