Take an array of integers and create an array of all the possible permutations in JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

We are required to write a function that does the following −

  • takes an array of integers as an argument (e.g. [1,2,3,4])

  • creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 (i.e., the length of original array)

Example

The code for this will be −

const arr = [1, 2, 3, 4];
const permute = (arr = [], res = [], used = []) => {
   let i, ch;
   for (i = 0; i < arr.length; i++) {
      ch = arr.splice(i, 1)[0];
      used.push(ch);
      if (arr.length === 0) {
         res.push(used.slice());
      }
      permute(arr, res, used);
      arr.splice(i, 0, ch);
      used.pop();
   };
   return res;
};
console.log(permute(arr));

Output

And the output in the console will be −

[
   [ 1, 2, 3, 4 ], [ 1, 2, 4, 3 ],
   [ 1, 3, 2, 4 ], [ 1, 3, 4, 2 ],
   [ 1, 4, 2, 3 ], [ 1, 4, 3, 2 ],
   [ 2, 1, 3, 4 ], [ 2, 1, 4, 3 ],
   [ 2, 3, 1, 4 ], [ 2, 3, 4, 1 ],
   [ 2, 4, 1, 3 ], [ 2, 4, 3, 1 ],
   [ 3, 1, 2, 4 ], [ 3, 1, 4, 2 ],
   [ 3, 2, 1, 4 ], [ 3, 2, 4, 1 ],
   [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ],
   [ 4, 1, 2, 3 ], [ 4, 1, 3, 2 ],
   [ 4, 2, 1, 3 ], [ 4, 2, 3, 1 ],
   [ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ]
]
raja
Published on 21-Nov-2020 13:53:08
Advertisements