
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ]
- Related Articles
- Snail Trail Problem in JavaScript
- Factorial recursion in JavaScript
- Audit Trail in DBMS
- Recursive Staircase problem in JavaScript
- Distributing Bananas Problem in JavaScript
- What is difference between trail balance and adjusted trail balance?
- 2 Key keyboard problem in JavaScript
- Meeting Rooms 2 problem in JavaScript
- Expressive words problem case in JavaScript
- Crack Alphabets fight problem in JavaScript
- Recursion - Sum Nested Array in JavaScript
- Calculating factorial by recursion in JavaScript
- How to Understand Recursion in JavaScript?
- The algorithm problem - Backtracing pattern in JavaScript
- How does recursion function work in JavaScript?

Advertisements