Monday, December 11, 2023

Permutations of a set of alphabets using JavaScript (A problem of recursion)

Problem

In the given problem statement we are asked to generate every possible permutation of the array given as input by the in JavaScript going from brute force method to optimized solution. What is Permutation of Array in JavaScript? Permutation of Array refers to the shuffling and ordering of elements present in an array. It generates all possible ways or arrangements of elements using the array as input source of it. If we have an array of n elements in javascript, it generates n! possible ways to order and output elements. The permutation of elements is the core of solving problem statement where the input and output can be visualized as follows : const arr = [ 1 , 2 , 3 ] ; // generate all permutations [ 1 , 2 , 3 ] [ 1 , 3 , 2 ] [ 2 , 1 , 3 ] [ 2 , 3 , 1 ] [ 3 , 1 , 2 ] [ 3 , 2 , 1 ]

Solution

function solution(A) { let resultArr = [] if (A.length > 1) { for (let i = 0; i < A.length; i++) { const currentElement = A[i]; otherElements = A.slice(0,i).concat(A.slice(i+1)); subPermutations = solution(otherElements); for (let j = 0; j < subPermutations.length; j++) { resultArr.push([currentElement].concat(subPermutations[j])); } } } else if(A.length == 1) { return [A] } return resultArr } console.log(solution(['A', 'B']))
[ Ref ]

No comments:

Post a Comment