Algorithm to find all possible permutations of a string or array

9.55K viewsProgramming
0

How can I implement a generic algorithm which generates all possible permutations of a string or array elements ?

Answered question
0

Below Javascript code does that in a nutshell:-

window.onload = init;    // patch init function to window onload event
 /* init function to be called on window load */
 function init() {
     console.log(permuteString('', 'abcd'));
     console.log(permuteArray('', ['William', 'Henry', 'Gates', 'Junior']));
 }
 
/* finds permutations of all characters of a string */
function permuteString(prefix, string) {
  var n = string.length;
  if (n === 0) {
   console.log(prefix);
  } else {
    for (var index = 0; index < n; index++) {
   permuteString(prefix.concat(string[index]), string.slice(0, index).concat(string.slice(index + 1, n)));
    }
  }
  return "Complete";
 }
/* same function slightly modified for an array with an extra space delimiter */
function permuteArray(prefix, string) {
  var n = string.length;
  if (n === 0) {
   console.log(prefix);
  } else {
    for (var index = 0; index < n; index++) {
   // Note:- space has been concatenated to distinguish/delimit between different array elements
   permuteArray(prefix.concat(string[index])+' ', string.slice(0, index).concat(string.slice(index + 1, n)));
    }
  }
  return "Complete";
 }

Changed status to publish
You are viewing 1 out of 2 answers, click here to view all answers.
Write your answer.

Categories