Snail Trail Problem in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array like this −

const arr = [
   [1, 2, 3, 4],
   [12,13,14,5],
   [11,16,15,6],
   [10,9, 8, 7]
];

The array is bound to be a square matrix.

We are required to write a JavaScript function that takes in this array and constructs a new array by taking elements and spiraling in until it converges to center. A snail trail spiraling around the outside of the matrix and inwards.

Therefore, the output for the above array should be −

const output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

Therefore, let’s write the code for this function. We will solve this problem using recursion.

Example

The code for this will be −

const arr = [
   [1, 2, 3, 4],
   [12,13,14,5],
   [11,16,15,6],
   [10,9, 8, 7]
];
const spiralForm = arr => {
   return arr.length > 1 ?
   arr.splice(0,1)[0]
   .concat(spiralForm(arr[0].map((c, i) => {
      return arr.map(r => r[i]);
   })
   .reverse())) :
   arr[0]
}
console.log(spiralForm(arr));

Output

The output in the console will be −

[
   1, 2, 3, 4, 5, 6,
   7, 8, 9, 10, 11, 12,
   13, 14, 15, 16
]
raja
Published on 22-Oct-2020 13:22:54
Advertisements