Last active
October 15, 2017 16:16
-
-
Save shailrshah/d5bffe598512c2f4c881c959f5f4583f to your computer and use it in GitHub Desktop.
A function to compute all the possible permutations of a given string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import java.util.ArrayList; | |
import java.time.Instant; | |
import java.time.Duration; | |
class PermuteString { | |
static List<String> permutations = new ArrayList<>(); | |
private static void permuteHelper(String availableChars, String permutationSoFar) { | |
if(availableChars.length() == 0){ | |
permutations.add(permutationSoFar); | |
return; | |
} | |
for(int i = 0; i < availableChars.length(); i++) { | |
char currentChar = availableChars.charAt(i); | |
String start = availableChars.substring(0, i); | |
String end = availableChars.substring(i+1); | |
permuteHelper(start+end, permutationSoFar + currentChar); | |
} | |
} | |
private static int fact(int n) { | |
if(n == 0 || n == 1) | |
return 1; | |
else return n * fact(n-1); | |
} | |
private static void permute(String str){ | |
permuteHelper(str, ""); | |
} | |
public static void main(String[] args) { | |
System.out.println("There will be " + fact(args[0].length()) + " permutations."); | |
Instant before = Instant.now(); | |
permute(args[0]); | |
Instant after = Instant.now(); | |
Duration time = Duration.between(before, after); | |
System.out.println(time.getSeconds() + " seconds have elapsed."); | |
permutations.forEach(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment