mirror of
https://bitbucket.org/Mattrixwv/csclasses.git
synced 2025-12-06 18:23:58 -05:00
Added functions to get all permutations of a string
This commit is contained in:
@@ -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<string> GetPermutations(string master){
|
||||
return GetPermutations(master, 0);
|
||||
}
|
||||
public static List<string> GetPermutations(string master, int num){
|
||||
List<string> perms = new List<string>();
|
||||
//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<string> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user