3

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

1 Answer 1

0

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);
}

}

Sign up to request clarification or add additional context in comments.

4 Comments

You are welcome. If it is a right answer don't be hesitate to put correct answer flag ;)
And do you have any non-recursive way to solve this problem efficiently
@alantheweasel If you want a better way to solve it non recursively, you will have to post another question.
@alantheweasel this post will help you. stackoverflow.com/questions/2799078/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.