From 3b48a61fe77764c9c23d1af01c32514c53356df0 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Fri, 4 Sep 2020 13:33:11 -0400 Subject: [PATCH] Added functions to get all permutations of a string --- CSClasses/Algorithms.cs | 43 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/CSClasses/Algorithms.cs b/CSClasses/Algorithms.cs index 592bf72..de669cc 100644 --- a/CSClasses/Algorithms.cs +++ b/CSClasses/Algorithms.cs @@ -607,5 +607,48 @@ namespace mee{ } return prod; } + //This is a function the creates all permutations of a string and returns a list of those permutations + public static List GetPermutations(string master){ + return GetPermutations(master, 0); + } + public static List GetPermutations(string master, int num){ + List perms = new List(); + //Check if the number is out of bounds + if((num >= master.Length) || (num < 0)){ + //Do nothing and return an empty list + } + //If this is the last possible recurse just return the current string + else if(num == (master.Length - 1)){ + perms.Add(master); + } + //If there are more possible recurses, the recurse with the current permutation + else{ + List temp = GetPermutations(master, num + 1); + perms.AddRange(temp); + //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(int cnt = 1;(num + cnt) < master.Length;++cnt){ + master = SwapString(master, num, (num + cnt)); + temp = GetPermutations(master, num + 1); + perms.AddRange(temp); + master = SwapString(master, num, (num + cnt)); + } + + //The array is not necessarily in alpha-numeric order. So if this is the full array sort it before returning + if(num == 0){ + perms.Sort(); + } + } + + //Return the list that was build + return perms; + } + public static string SwapString(string str, int first, int second){ + char[] tempStr = str.ToCharArray(); + char temp = str[first]; + tempStr[first] = tempStr[second]; + tempStr[second] = temp; + return new string(tempStr); + } } }