Advertisement
josebaperu

Untitled

Jul 20th, 2015
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. package basepkg;
  2.  
  3. import java.util.TreeSet;
  4. import java.util.Set;
  5.  
  6. public class MainForPermutation {
  7.    
  8.       public Set<String> permute(String str){
  9.         //Using a set will get rid of duplicates  
  10.         Set<String> set = new TreeSet<String>();
  11.         // Condition for termination
  12.         if (str.length() == 1){
  13.                 set.add(str);
  14.         }else{
  15.             // Removes the character at index i
  16.             for (int i=0; i<str.length(); i++){
  17.                 String pre = str.substring(0, i);
  18.                 String post = str.substring(i+1);
  19.                 String remaining = pre+post;
  20.             // Concatenation process of remainder characters
  21.             for (String permutation : permute(remaining)){
  22.                 set.add(str.charAt(i) + permutation);
  23.             }
  24.           }
  25.         }
  26.         return set;
  27.       }
  28.      
  29.       public static void main(String[] args) throws IllegalArgumentException{
  30.  
  31.       MainForPermutation mainClass;
  32.       String exThrown="Exception has occured, reason : ";
  33.       // throws exception if argument is null :: command line
  34.         if (args.length <= 0){
  35.             System.err.println(exThrown+"NULL argument passed on");
  36.             throw new IllegalArgumentException();
  37.         }
  38.        
  39.       mainClass = new MainForPermutation();
  40.        
  41.         for (int i =0;i<args.length;i++){
  42.            
  43.             if (args[i].matches("^[A-Za-z0-9]+$")){
  44.                 System.out.println(mainClass.permute(args[i]));
  45.                 // prints on console, sorted permuted characters
  46.             }else{
  47.                 System.err.println(exThrown+"Invalid chars in string");
  48.                 throw new IllegalArgumentException();
  49.                   // throws exception if argument is not alphanumeric  (~#@*+%{}<>[]|“”\_^) not allowed
  50.             }
  51.         }
  52.       }
  53.    
  54. /*    Expected result set  (https://www.codeeval.com/public_sc/14/)
  55.      
  56.       aht,ath,hat,hta,tah,tha
  57.       abc,acb,bac,bca,cab,cba
  58.       6Zu,6uZ,Z6u,Zu6,u6Z,uZ6   */
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement