-
-
Save thedillonb/7d0d509dcaae811af668 to your computer and use it in GitHub Desktop.
Recursive implementation of string characters permutation covering all possible cases without duplication
This file contains 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 buf = permute(str.slice(0, i).concat(str.slice(i+1))) | |
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
Test!