Last active
September 1, 2015 18:44
-
-
Save h2non/06cdb6e6b87ca67373b8 to your computer and use it in GitHub Desktop.
Recursive implementation of string characters permutation covering all possible cases without duplication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Recursive implementation of string characters permutation | |
* covering all possible cases without duplication | |
*/ | |
function permute(str) { | |
var stack = [] | |
if (str.length === 1) { | |
return [ str ] | |
} | |
for (var i = 0; i < str.length; i += 1) { | |
var char = str[i] | |
var head = str.slice(0, i) | |
var tail = str.slice(i+1) | |
var buf = permute(head.concat(tail)) | |
for (var x = 0; x < buf.length; x += 1) { | |
stack.push(char + buf[x]) | |
} | |
} | |
return stack | |
} | |
var result = permute('abc') | |
console.log(JSON.stringify(result, null, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment