I came across this challenge from codewars. I wish to know how to solve this problem. The problem description is given below.
Its elements are in range[1..n^2]. The matrix is filled by rings, from the outwards the innermost. Each ring is filled with numbers in the following way:
- The first number is written in the top left corner;
- The second number is written in the top right corner;
- The third number is written in the bottom right corner;
- The fourth number is written in the bottom left corner;
- Each next number is written next to the number written 4 steps before it, until the ring is filled.
The matrix is constructed when all numbers are written.```
Given the size of the hole, return the number written at (a, b
) - you may use any consistent indexing, but please specify if (a, b
) is anything other than 0-indexed and row-major.
Example
For n = 4, a = 1, b = 1
, the output should be 13
.
The hole looks like this:
[ [ 1, 5, 9, 2 ]
[ 12, 13, 14, 6 ]
[ 8, 16, 15, 10 ]
[ 4, 11, 7, 3 ]
]
The element at (1, 1) is 13
Test cases
(a, b
) is 0-indexed and row-major here.
n a b result
1 0 0 1
2 0 0 1
3 0 0 1
4 0 0 1
2 0 1 2
3 0 1 5
3 1 1 9
4 1 1 13
4 2 1 16
5 2 3 22