From 39199ed1378a0735985df7f44f5275021689ca39 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Thu, 8 Apr 2021 13:20:39 -0400 Subject: [PATCH] Added function to get all permutations of a string --- Algorithms.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Algorithms.ts b/Algorithms.ts index bd31fa6..d3625f7 100644 --- a/Algorithms.ts +++ b/Algorithms.ts @@ -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; +}