I made a code that should show the entire combination of permutations of elements in an array.
package com.company;
import java.util.ArrayList;
import java.lang.Math;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
first(3);
}
static int factorial(int n) {
int res = 1;
for (int i = 2; i <= n; i++) {
res *= i;
}
return res;
}
static void first(int n){
int[] array = new int[n];
for(int i = 0; i < n;i++){
array[i]=i+1;
}
for(int i = 0; i < factorial(n);i++){
for(int j = 0; j < n; j++) {
if(j==n-1){
continue;
}
int t = array[j];
array[j] = array[j+1];
array[j+1] = t;
}
for(int k =0;k<n;k++){
System.out.print(array[k]);
}
System.out.println();
}
}
}
What should it be:
123 213 231 132 312 321
But it turns out like this:
231 312 123 231 312 123
How can a permutation be done the way it should?