Hello folks. I am stuck in a problem where I must pair objects of an array with unique partners.

I have one array.
I must pair each element to each other.
Incorrect pairing algorithm would result with repetitions, and pairing with itself.

e.g.

String[] codesArray = {"A", "B", "C"};

For this array (codesArray), the pairing (correct output) would be:

/*
Correct:
A-B
A-C
B-C
*/

My attempt,
I have tried to do a 2-nested forloop:

for each element i in codesArray 
   for each element j in codesArray 
       pairThese(i,j)

...which gives me the incorrect output.

Incorrect output:

/*
Wrong:
A-A  //Can't pair with itself.
A-B
A-C
B-A  //Already paired previously.
B-B  //Can't pair with itself.
B-C
C-A  //Already paired previously.
C-B  //Already paired previously.
C-C  //Already paired previously.
*/

How would I be able to implement an algorithm to achieve the correct output?
(Also, I realise that this might be a common problem. What would I search for in order to find similar problems? Key words?)

Cheers.

Recommended Answers

All 2 Replies

If you look at the correct solution you will notice that each pair consists of an element and a second element that comes later in the array, ie

for each element i in codesArray
  for each element j that appears after i in codesArray
    pairThese(i,j)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.