Advertisement
scottashipp

Permutation Generator 3

Apr 29th, 2013
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. package com.scottshipp;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Scanner;
  6.  
  7. public class PermutationGenerator3 {
  8.    
  9.     private static String inputWithoutC(String input, int index) {
  10.         String inputWithoutC = "";
  11.         char[] temp = input.toCharArray();
  12.         for(int i = 0; i < temp.length; i++) {
  13.             if(i != index) {
  14.                 inputWithoutC += temp[i];
  15.             }
  16.         }
  17.         return inputWithoutC;
  18.     }  
  19.    
  20.     private static ArrayList<String> generatePermutationsOfAString(String input) {
  21.         //null check
  22.         if(input == null) {
  23.             return null;
  24.         }
  25.        
  26.         ArrayList<String> subPermutations = new ArrayList<String>();
  27.         ArrayList<String> permutations = new ArrayList<String>();
  28.        
  29.         char[] temp = input.toCharArray();
  30.        
  31.         //base case: two letters, return each one plus their two permutations
  32.         if(temp.length == 2) {
  33.             permutations.add(String.valueOf(temp[0]));
  34.             permutations.add(String.valueOf(temp[1]));
  35.             permutations.add(String.valueOf(temp[0]) + String.valueOf(temp[1]));
  36.             permutations.add(String.valueOf(temp[1]) + String.valueOf(temp[0]));
  37.             return permutations;
  38.         }
  39.        
  40.         for(int i = 0; i < temp.length; i++) {
  41.             char c = temp[i];
  42.             subPermutations = generatePermutationsOfAString(inputWithoutC(input, i));
  43.             permutations.add(String.valueOf(c));
  44.             for(String s : subPermutations) {          
  45.                 permutations.add(String.valueOf(c) + s);
  46.             }
  47.         }
  48.         return permutations;
  49.     }
  50.        
  51.     /**
  52.      * @param args
  53.      */
  54.     public static void main(String[] args) {
  55.         Scanner readUserInput = new Scanner(System.in);
  56.         System.out.println("Enter the source string: ");
  57.         String permuteThis = readUserInput.next();
  58.         System.out.println("\nThe resulting permutations are: ");
  59.         //begin new lines
  60.         ArrayList<String> permutations = generatePermutationsOfAString(permuteThis);
  61.         Collections.sort(permutations);
  62.         //end new lines
  63.         for(String s : permutations) {
  64.             System.out.print(s + "\t");
  65.         }
  66.  
  67.     }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement