Skip to content

Instantly share code, notes, and snippets.

@TheoOkafor
Created May 30, 2022 12:59
Show Gist options
  • Save TheoOkafor/b9e5a5817aff503d046f8f125fdf4843 to your computer and use it in GitHub Desktop.
Save TheoOkafor/b9e5a5817aff503d046f8f125fdf4843 to your computer and use it in GitHub Desktop.
An algorithm that prints all permutations of a string
/**
* Returns an array of strings, with different positions of char in the string - str
*/
function swapAll(str, char) {
const result = [];
for (let i = 0; i <= str.length; i += 1) {
const newStr = `${str.slice(0, i)}${char}${str.slice(i, str.length)}`;
result.push(newStr);
}
return result;
}
/**
* A function that prints all permutations of a string
*/
function permutate(str, arr=[], level=1) {
if (level >= str.length) {
return arr;
} else {
if (arr.length <= 0) {
const substr = str.substring(0, level);
const newArr = swapAll(substr, str[level]);
return permutate(str, newArr, level + 1);
} else {
let newArr = [];
arr.forEach((permutedStr) => {
const swaps = swapAll(permutedStr, str[level]);
newArr = [...newArr, ...swaps];
});
return permutate(str, newArr, level + 1);
}
}
}
// Example:
permutate('abc'); // ['cba', 'bca', 'bac', 'cab', 'acb', 'abc']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment