Advertisement
josebaperu

Untitled

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