Guest User

Permutation

a guest
Jun 22nd, 2017
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1. package permutation;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class Permutation {
  7.    
  8.     List<String> results = new ArrayList<String>();
  9.    
  10.     public static void main(String [] args){
  11.         String inputstring = "STB";
  12.         char[] input = inputstring.toCharArray();
  13.         int n = input.length-1;
  14.         Permutation p = new Permutation();
  15.         p.permute(input, 0, n);
  16.     }
  17.     /**
  18.      * Recusive method to calculate the permutation of a given String.
  19.      * A permutation is the rearrangement of elements of an ordered list
  20.      * - further information @ http://mathworld.wolfram.com/Permutation.html
  21.      * @param input
  22.      * @param i
  23.      * @param n
  24.      */
  25.     private void permute(char[] input, int i, int n){
  26.         if(i == n){
  27.             System.out.println(input);
  28.             results.add(new String(input));
  29.         }
  30.         else{
  31.         for(int j = i; j <= n; j++){
  32.             swap(input, i, j);
  33.             permute(input, i+1, n);
  34.             swap(input, i, j);
  35.         }
  36.         }
  37.     }
  38.     private char[] swap(char[] input, int i, int j){
  39.         char help = input[i];
  40.         input[i] = input[j];
  41.         input[j] = help;       
  42.         return input;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment