Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.TreeSet;
- import java.util.Set;
- public class MainForPermutation {
- public Set<String> permute(String str){
- //Using a set will get rid of duplicates
- Set<String> set = new TreeSet<String>();
- // Condition for termination
- if (str.length() == 1){
- set.add(str);
- }else{
- // Removes the character at index i
- for (int i=0; i<str.length(); i++){
- String pre = str.substring(0, i);
- String post = str.substring(i+1);
- String remaining = pre+post;
- // Concatenation process of remainder characters
- for (String permutation : permute(remaining)){
- set.add(str.charAt(i) + permutation);
- }
- }
- }
- return set;
- }
- public static void main(String[] args) throws IllegalArgumentException{
- MainForPermutation mainClass;
- String exThrown="Exception has occured, reason : ";
- // throws exception if argument is null @ command line
- if (args.length <= 0){
- System.err.println(exThrown+"NULL argument passed on");
- throw new IllegalArgumentException();
- }
- mainClass = new MainForPermutation();
- for (int i =0;i<args.length;i++){
- if (args[i].matches("^[A-Za-z0-9]+$")){
- System.out.println(mainClass.permute(args[i]));
- // prints out in console, permuted characters
- }else{
- System.err.println(exThrown+"Invalid chars in string");
- throw new IllegalArgumentException();
- // throws exception if arguments contain non alphanumeric chars (~#@*+%{}<>[]|“”\_^) not allowed
- }
- }
- }
- /* Expected result set (https://www.codeeval.com/public_sc/14/)
- aht,ath,hat,hta,tah,tha
- abc,acb,bac,bca,cab,cba
- 6Zu,6uZ,Z6u,Zu6,u6Z,uZ6 */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement