Added function to get all permutations of a string

This commit is contained in:
2021-04-08 13:20:39 -04:00
parent 6443a56de8
commit 39199ed137

View File

@@ -498,3 +498,45 @@ export function getProdBig(ary: bigint[]): bigint{
ary.forEach(a => prod *= a);
return prod;
}
//This is a function that creates all permutations of a string and returns a vector of those permutations
export function getPermutations(master: string): string[]{
return getPermutationsHelper(master, 0);
}
function getPermutationsHelper(master: string, num: number): string[]{
let perms: string[] = [];
//Check if the number is out of bounds
if((num >= master.length) || (num < 0)){
//Do nothing and return an empty array
}
//If this is the last possible recurse just return the current string
else if(num == (master.length - 1)){
perms.push(master);
}
//If there are more possible recurses, recurse with the current permutation
else{
let temp: string[] = getPermutationsHelper(master, num + 1);
temp.forEach(str => perms.push(str));
//You need to swap the current letter with every possible letter after it
//The ones needed to swap before will happen automatically when the function recurses
for(let cnt = 1;(num + cnt) < master.length;++cnt){
master = swapString(master, num, (num + cnt));
temp = getPermutationsHelper(master, num + 1);
temp.forEach(str => perms.push(str));
master = swapString(master, num, (num + cnt));
}
//The array is not necessarily in alph-numeric order. So if this is the full array sort it before returning
if(num == 0){
perms.sort();
}
}
//Return the array that was build
return perms;
}
function swapString(str: string, first: number, second: number): string{
let tempStr: string = str.substr(0, first) + str[second] + str.substr(first + 1, second - first - 1) + str[first] + str.substr(second + 1);
return tempStr;
}