Advertisement
Guest User

Permute2

a guest
May 3rd, 2012
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package einsteinsriddle;
  6.  
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. /**
  11.  * @author ??? && Joel Brito
  12.  */
  13. public class Permute2 {
  14.  
  15.     private static Object[] input;
  16.     private static int outputIndex;
  17.     private static List<List<Object>> output;
  18.  
  19.     public Permute2() {
  20.         outputIndex = 0;
  21.     }
  22.  
  23.     public List<List<Object>> getPermutation(Object[] input) {
  24.         this.input = input;
  25.         this.output = new ArrayList<>();
  26.  
  27.         permutations(0);
  28.         return output;
  29.     }
  30.  
  31.     private static void permutations(int offset) {
  32.         if (input.length - offset == 1) {
  33. // Input now contains a permutation, here I store it in output,
  34. // but you can do anything you like with it
  35.  
  36.             List<Object> tmp = new ArrayList<>();
  37.             for (Object o : input) {
  38.                 tmp.add(o);
  39.             }
  40.             output.add(tmp);
  41.             return;
  42.         }
  43.  
  44.         Object a = input[offset];
  45.  
  46.         for (int i = offset; i < input.length; i++) {
  47. // Swap elements
  48.             Object b = input[i];
  49.             input[i] = a;
  50.             input[offset] = b;
  51.  
  52.             permutations(offset + 1);
  53.  
  54. // Restore element
  55.             input[i] = b;
  56.         }
  57.  
  58.         input[offset] = a;
  59.     }
  60.  
  61.     private static int factorial(int n) {
  62.         return n == 1 ? n : n * factorial(n - 1);
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement