Skip to content

Instantly share code, notes, and snippets.

@thedillonb
Forked from h2non/permute-characters.js
Last active August 30, 2015 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thedillonb/7d0d509dcaae811af668 to your computer and use it in GitHub Desktop.
Save thedillonb/7d0d509dcaae811af668 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 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))
@thedillonb
Copy link
Author

Test!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment