Java Nested Array to Recursion Method

438 views Asked by At

Here is my code, which is being used to find all the combination from an array Is there any recursive way to increase the flexibilty of coding ?

Result of here : 1324 1342 1234 1243 1432 1423 3124 3142 3214 3241 3412 3421 2134 2143 2314 2341 2413 2431 4132 4123 4312 4321 4213 4231

class Main {

  // Find all combination from an array
  public static void findAllConbinationFromArray(int ary[]){
    for(int i = 0 ; i < ary.length ; i++){
      for(int j = 0 ; j < ary.length ; j++){
        for(int k = 0 ; k < ary.length ; k++){
          for(int l = 0 ; l < ary.length ; l++){
            if(check(i, j, k, l)){
              System.out.print(ary[i] + "" + ary[j] + "" + ary[k] + "" + ary[l]);
              System.out.println(); 
            }
          }
        }
      }
    }
  }

  // Check and skip if it selects same value
  public static boolean check(int ... elemt){

    for(int i = 0 ; i < elemt.length ; i++){
      int current = elemt[i];
      for(int j = 0 ; j < elemt.length ; j ++){
        if(i != j){
          if(current == elemt[j])
            return false;
        }
      }
    }
    return true;
  }

  public static void main(String[] args) {
    int ary[] = {1, 3, 2, 4};
    findAllConbinationFromArray(ary);
  }
}
1

There are 1 answers

4
Chamin Wickramarathna On BEST ANSWER

This is a recursive way to produce all permutations of an array.

public class Permute {

void swap(int[] arr, int x, int y) {
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

void permute(int[] arr) {
    permute(arr, 0, arr.length - 1);
}

//i - start index
//n - end index
void permute(int[] arr, int i, int n) {
    int j;
    if (i == n)
        System.out.println(Arrays.toString(arr));
    else {
        for (j = i; j <= n; j++) {
            swap(arr, i, j);
            permute(arr, i + 1, n);
            swap(arr, i, j); // swap back
        }
    }
}

public static void main(String[] args) {
    int arr[] = { 1, 2, 3, 4 };
    new Permute().permute(arr);
}

}