Permutations for string
Last active
December 30, 2021 20:45
-
-
Save GGrassiant/258622d05a73137b1218a7f8c0dda8d6 to your computer and use it in GitHub Desktop.
All permutations for sting
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
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