-2

Let's say we have an array of integers as follows:

int[] sol = new int[] {3, 5, 1, 2, 4};

I want to enumerate all the possible arrays that could be obtained when choosing 2 arbitrary elements of the array and swapping them (i.e. if we swap the number 3 with the number 2 we get {2, 5, 1, 3, 4}). There are, for this case, 10 possible swaps of 2 elements.

How can all of the possible enumerations be shown with Java?

chb
  • 1,727
  • 7
  • 25
  • 47
  • 1
    Add an example of what you have tried and describe what's the problem with your current solution. – ailav May 05 '18 at 23:39

1 Answers1

0

The first thing you need to do is figure out how many different possible combinations that could exist. In this case, since you're choosing 2 numbers: 3 for 5 3 for 1 3 for 2 3 for 4

5 for 3 5 for 1 5 for 2 5 for 4

and so on so forth. Since each number has 4 other number is can be paired with we can figure out the total by doing the following equation: numberOfElementsInVector*4. In this case, we get 20. this means that we only need to loop for 20 times. We also need to keep track of what results we've already gathered. For that, we will store strings in an ArrayList. Now what we'll do is the following double for loop:

ArrayList<String> results = new ArrayList<>();
for(int i = 0; i < sol.length; i++){
    for(int j = 0; j < sol.length; j++){
        String result = sol[i] + "," + sol[j] + "";
        if(!results.contains(result) && sol[i] != sol[j]){
           results.add(result);
        }
    }
}
System.out.printLn(results.toString());

This code will systematically go through any length of Array and give you all 2 number combos.

Kwright02
  • 777
  • 3
  • 21
  • the solution I gave isn't 100% what he asked for anyways and I did that purposefully. I was merely trying to give an insight into how the OP could go about doing such a thing. My code above would give you the following output with his sol[] : [3,5, 3,1, 3,2, 3,4, 5,3, 5,1, 5,2, 5,4, 1,3, 1,5, 1,2, 1,4, 2,3, 2,5, 2,1, 2,4, 4,3, 4,5, 4,1, 4,2] – Kwright02 May 05 '18 at 23:58