Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Last active December 30, 2021 20:45
Show Gist options
  • Save GGrassiant/258622d05a73137b1218a7f8c0dda8d6 to your computer and use it in GitHub Desktop.
Save GGrassiant/258622d05a73137b1218a7f8c0dda8d6 to your computer and use it in GitHub Desktop.
All permutations for sting
function permutations(string) {
if (!string || typeof string !== "string"){
return "Please enter a string"
}
if (!!string.length && string.length < 2 ){
console.log('letter', string);
return [string]
}
let permutationsArr = [];
for (let i = 0; i < string.length; i++){
let char = string[i]
console.log('char', char, i);
// if (string.indexOf(char) !== i) {
// continue;
// }
let remainder = string.slice(0, i) + string.slice(i + 1, string.length);
console.log('remainder', remainder);
for (let permutation of permutations(remainder)){
console.log(char, permutation);
permutationsArr.push(char + permutation);
console.log('returned', permutationsArr);
}
}
return permutationsArr;
}
// permutations('a');
// permutations('ab');
permutations('abs');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment