Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Combination of elements in array in couples

I have an array of elements (even number) and I want to get all possible combinations of them in couples.

If the array is

String[] test = new String[4]; 
String[] test= {"e1","e2","e3","e4"};

The output should be:

Combination1 e1-e2 , e3-e4
Combination2 e1-e3 , e2-e4
Combination3 e1-e4 , e2-e3
Combination4 e4-e1 , e3-e2
Combination5 e3-e1 , e4-e2
Combination6 e2-e1 , e4-e3
like image 200
user3189770 Avatar asked Dec 03 '25 08:12

user3189770


1 Answers

Link to previous answer


String[] test = {"e1","e2","e3","e4"};

for (int i = 0; i < test.length; i++) {

    for (int j = i + 1; j < test.length; j++) {

        System.out.print(test[i] + " - " + test[j]);

        boolean foundExtra = false;

        for (int k = 0; k < test.length && !foundExtra; k++)
        {
            if (k != j && k != i)
            {
                for (int l = 0; l < test.length; l++)
                {
                    if (l != k && l != j && l != i)
                    {
                        System.out.println(" , " + test[k] + " - " + test[l]);
                        foundExtra = true;
                        break;
                    }
                }
            }
        }
    }
}

Will give the output:

e1 - e2 , e3 - e4
e1 - e3 , e2 - e4
e1 - e4 , e2 - e3
e2 - e3 , e1 - e4
e2 - e4 , e1 - e3
e3 - e4 , e1 - e2

This is not the output you put in your question, but I believe this is the output you want, judging from your sports teams comment.

Don't be scared of the loops - I did this in one try because I thought threw it easily.

What I was thinking: Find all of the combinations, like in my previous answer. That's what I started with. Next thing I did (the last 2 of 4 loops - k and l), was check for the other teams that were left.

So cycle through all of the elements, check if i and j were not already used, then that was k. Then, cycle through all of the elements again, check if i, j, and k were not already used, then that was l.

like image 121
Michael Yaworski Avatar answered Dec 05 '25 23:12

Michael Yaworski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!