Skip to content

Instantly share code, notes, and snippets.

@h2non
Last active September 1, 2015 18:44
Show Gist options
  • Save h2non/06cdb6e6b87ca67373b8 to your computer and use it in GitHub Desktop.
Save h2non/06cdb6e6b87ca67373b8 to your computer and use it in GitHub Desktop.
Recursive implementation of string characters permutation covering all possible cases without duplication
/**
* 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