Added a function to get all permutations of a

string
This commit is contained in:
2019-03-24 15:43:22 -04:00
parent 8f4d8664f4
commit 8fe685f7e0
3 changed files with 107 additions and 3 deletions

Binary file not shown.

View File

@@ -1,7 +1,7 @@
//Java/JavaClasses/Algorithms.java
//Matthew Ellison
// Created: 03-02-19
//Modified: 03-03-19
//Modified: 03-24-19
//This class holds many algorithms that I have found it useful to keep around
//As such all of the functions in here are static and meant to be used as stand alone functions
/*
@@ -729,6 +729,7 @@ public class Algorithms{
//Return the product of all elements
return product;
}
//This function returns true if key is found in ary
public static Boolean isFound(ArrayList<Integer> ary, Integer key){
//Look through every element in the array, looing for the key element
for(Integer num : ary){
@@ -762,4 +763,50 @@ public class Algorithms{
//If you made it to the end of the array without finding a match return false because the element was not found
return false;
}
//This is a function that creates all permutations of a string and returns a vector of those permutations.
public static ArrayList<String> getPermutations(String master){
return getPermutations(master, 0);
}
private static ArrayList<String> getPermutations(String master, Integer num){
ArrayList<String> perms = new ArrayList<String>();
//Check if the number is out of bounds
if((num >= master.length()) || (num < 0)){
//Do nothing and return an empty arraylist
}
//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, recurse with the current permutation
else{
ArrayList<String> temp = new ArrayList<String>();
temp = getPermutations(master, num + 1);
perms.addAll(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(Integer cnt = 1;(num + cnt) < master.length();++cnt){
master = swapString(master, num, (num + cnt));
temp = getPermutations(master, num + 1);
perms.addAll(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){
Collections.sort(perms);
}
}
//Return the arraylist that was built
return perms;
}
public static String swapString(String str, Integer first, Integer second){
char[] tempStr = str.toCharArray();
char temp = tempStr[first];
tempStr[first] = tempStr[second];
tempStr[second] = temp;
String swappedString = new String(tempStr);
return swappedString;
}
}