0

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.

Edited by thompsonSensibl: n/a

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by thompsonSensibl
1

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)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.