Guest User

Untitled

a guest
May 22nd, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. public class Perm {
  2.    private static void reverse(int[] values, int first, int last){
  3.       int temp;
  4.       if(first == last)
  5.           return;
  6.       --last;
  7.       while (first < last){
  8.          // swap first, last
  9.          temp = values[first];
  10.          values[first] = values[last];
  11.          values[last] = temp;
  12.  
  13.          ++first;
  14.          --last;
  15.       }
  16.    }
  17.  
  18.    private static boolean nextPerm(int[] values){
  19.         int i =  values.length - 1;
  20.  
  21.         if(values.length < 2)
  22.             return false;
  23.  
  24.         for(;;) {
  25.             int ii = i;
  26.             --i;
  27.             int temp;
  28.             if (values[i] < values[ii]) {
  29.                 int j = values.length;
  30.                 while (values[i] >= values[--j]);
  31.  
  32.                 // swap i, j
  33.                 temp = values[i];
  34.                 values[i] = values[j];
  35.                 values[j] = temp;
  36.  
  37.                 reverse(values, ii, values.length);
  38.                 return true;
  39.             }
  40.             if (i == 0) {
  41.                 reverse(values, 0, values.length);
  42.                 return false;
  43.             }
  44.         }
  45.     }
  46.  
  47.  
  48.    public static void main(String[] args){
  49.       int[] vals = {1,2,3,4,5, 6, 7 , 8 , 9, 10, 11, 12, 13};
  50.      int count=0;
  51.      do {
  52.          count++;
  53.      } while(nextPerm(vals));
  54.      System.out.println("Found "+count+" Permutations");
  55.    }
  56.  
  57. }
Add Comment
Please, Sign In to add comment