Recursion problem Snail Trail in JavaScript



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];

We will solve this problem using recursion.

Example

Following is the code −

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

This will produce the following output on console −

[   1,  2,  3,  4,  5,  6,   7,  8,  9, 10, 11, 12,  13, 14, 15, 16 ]
Updated on: 2020-10-01T10:24:06+05:30

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements