npm-spirilize-pattern
v1.0.2
Published
A spiral array is a square arrangement of the first N2 natural numbers, where the numbers increase sequentially as you go around the edges of the array spiraling inwards.
Downloads
3
Readme
npm-spirilize-pattern
A spiral array is a square arrangement of the first N2 natural numbers, where the numbers increase sequentially as you go around the edges of the array spiraling inwards.
Installation
npm i npm-spirilize-pattern
Usage
const test = require('npm-package-butet')
The input for this problem will be a matrix, or multidimensional array, which will be represented by N arrays each of N length, and your goal is to print the matrix in a spiral order. For example, if the input is:
[[1, 2, 3], [4, 5, 6], 7, 8, 9]]
then this matrix should be printed out in a list like so:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
The spiral begins at the top left of the matrix and loops around it towards the center in a clockwise pattern. Below is a clever algorithm that uses recursion to print a matrix in spiral order:
Algorithm
- Every other iteration through the matrix peel off the first row and last column of the matrix. ...So for the above array we should get: [[1, 2, 3], [6, 9]]. Store these elements in a list and then pass the modified matrix to another function. The modified matrix currently looks like this:
[[4, 5],[7, 8]]
- Now peel off the last row and first column from the matrix, reverse each one, and add them to the previous list. Our spiral list should look like the following so far:
[[1, 2, 3], [6, 9], [8, 7], [4]].
- Now continue from step 1 until the matrix has no elements left and return the final spiraled list.
1 | 2 | 3 | 4 | 5 6 | 7 | 8 | 9 | 10 11 | 12 | 13 | 14 | 15 16 | 17 | 18 | 19 | 20 21 | 22 | 23 | 24 | 25
Result
[ '1,2,3,4,5,10,15,20,25,24,23,22,21,16,11,6,7,8,9,14,19,18,17,12,13' ]
Author
Butet Batak [[email protected]]
Licence
MIT @butetbatak