I am doing some practice where I have to find all the permutations of n numbers. I was given pseudo code, however, I am having difficulties translating it.
public void nextPerm(int[] a,int pivot,int suc){
suc = 0;
pivot = 0;
for(int i = a.length-1;; i--){
if( i+1 != a.length)
if(a[i] < a[i+1]){
pivot = i;
break;
} else if(pivot == 0){
reverseArray(a,pivot);//this just reverses the array from the right of the pivot point
System.out.println(a);
}
}
for(int i = a.length-1;;i--){
if(a[i] > a[pivot]){
suc = i;
break;
}
}
//swap pivot and suc
int place = a[pivot];
a[pivot] = a[suc];
a[place] = a[pivot];
reverseArray(a,pivot);
System.out.println(Arrays.toString(a));
}
private void reverseArray(int[] a,int pivot) {//make pivot the index which it will reverse to the right of
// TODO Auto-generated method stub
int[] place = new int[a.length-pivot-1];
int counter = 0;
for(int i = a.length-1; i > pivot;i--){
place[counter] = a[i];
counter++;
}
counter = 0;
int[] hold = new int[a.length];
for(int i = 0; i <= pivot;i++){
hold[i] = a[i];
counter++;
}
for(int i = 0; i < place.length;i++){
hold[counter] = place[i];
counter++;
}
System.out.println(Arrays.toString(hold));
}
This is what I have so far. Basically each time I run nextPerm
it adjusts an array to be another permutation. For more info check out the pages here: link to more info
Summary: nextPerm
finds all the possible perms one at a time by manually changing the array.