Hello everyone.
I have been struggling with this one for a few days now.
Here is the description:
Problem 14: Spiral Matrix
Write a program that reads from the console a positive integer number n
(1 ≤ n ≤ 20) and prints a matrix holding the numbers from 1
to n*n
in the form of square spiral like in the examples below.
Examples:
n | matrix |
---|---|
2 | 1 2 |
4 3 |
n | matrix |
---|---|
3 | 1 2 3 |
8 9 4 | |
7 6 5 |
Here is my 1/2 solution. It works from 1-10, but any larger number gives issues.
https://codeshare.io/ayLJOb
I have determined that the problem is some sort of Array limit of 100.
As you can see on the last line I have tried to overcome it with:
console.dir(arrA, {‘maxArrayLength’: null});
But still it doesn’t do the job.
I know there are other solutions, but I want to make this code work. Please, give me a way to deal with this JS limit.
My code is not explained in detail, so I will explain what happens in general.
- I create all the needed numbers from 1 to n*n but backwards.
- I create an array grid.
- Then I create a pattern based on the direction and number of indexes the spiral will ‘move’ from the center to the start.
3.1 - create the letters corresponding to the directions, r, u, l, d.
3.2 - create the corresponding numbers 1, 1, 2, 2…
3.3 - combine the 2 arrays in r1, u1, l2, d2… - Fill the grid with the corresponding numbers.
There are different patterns for even and odd numbers, but that is covered. There are different starting centers for even and odd numbers which are also covered.
The code get’s each number from “numbers” and the direction from “finalPattern”, then according the the 4 If cases, it uses them to fill the grid.
- Converts the array in to a string, then splits it in to the appropriate number of rows.
Also, do you have any, free code sharing platfrom that doesn’t expire in 24 hours?
Thank you for your time!