Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to insert an element into all positions in an array using recursion - JavaScript?
We are required to declare a function, let’s say insertAllPositions, which takes two arguments −
an element, x, and an array, arr. Functions must return an array of arrays, with each array corresponding to arr with x inserted in a possible position.
That is, if arr is the length N, then the result is an array with N + 1 arrays −
For example, the result of insertAllPositions(10, [1,2,3]) should be −
const output = [ [10,1,2,3], [1,10,2,3], [1,2,10,3], [1,2,3,10] ];
We are required to write this function purely using recursion.
Example
Following is the code −
const arr = [1, 2, 3];
const num = 10;
const insertAllPositions = (num, arr) => {
return arr.length ?
[[num, ...arr]]
.concat(insertAllPositions(num, arr.slice(1))
.map(el => {
return [arr[0]].concat(el);
})) :
[[num]]
};
console.log(insertAllPositions(num, arr));
Output
This will produce the following output on console −
[ [ 10, 1, 2, 3 ], [ 1, 10, 2, 3 ], [ 1, 2, 10, 3 ], [ 1, 2, 3, 10 ] ]
Advertisements