Algorithm to find all possible permutations of a string or array
How can I implement a generic algorithm which generates all possible permutations of a string or array elements ?
Anonymous Answered question
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"; }
goli202084 Changed status to publish