22
33import java .util .ArrayList ;
44import java .util .Collections ;
5+ import java .util .HashSet ;
56import java .util .List ;
7+ import java .util .Set ;
68
7- public final class UniquePairShuffle {
9+ public
10+ final class UniquePairShuffle {
811
9- private UniquePairShuffle () {
12+ private
13+ UniquePairShuffle () {
1014 // Prevent instantiation
1115 }
1216
@@ -19,7 +23,8 @@ private UniquePairShuffle() {
1923 * @return a list of unique pairs where each pair is represented as an integer
2024 * array of length 2
2125 */
22- public static List <int []> pairShuffle (int [] array ) {
26+ public
27+ static List <int []> pairShuffle (int [] array ) {
2328 List <int []> pairs = new ArrayList <>();
2429
2530 // Handle edge case: If the array length is odd, pairing is not possible
@@ -35,15 +40,25 @@ public static List<int[]> pairShuffle(int[] array) {
3540 // Shuffle elements to create random pairs
3641 Collections .shuffle (shuffledList );
3742
38- // Form pairs from the shuffled elements
43+ // Form pairs from the shuffled elements, avoiding duplicate pairs
44+ Set <String > uniquePairs = new HashSet <>();
3945 for (int i = 0 ; i < shuffledList .size (); i += 2 ) {
40- pairs .add (new int [] {shuffledList .get (i ), shuffledList .get (i + 1 )});
46+ int [] pair = new int []{shuffledList .get (i ), shuffledList .get (i + 1 )};
47+ String pairKey =
48+ Math .min (pair [0 ], pair [1 ]) + "-" + Math .max (pair [0 ], pair [1 ]);
49+
50+ // Ensure no repeated pairs
51+ if (!uniquePairs .contains (pairKey )) {
52+ pairs .add (pair );
53+ uniquePairs .add (pairKey );
54+ }
4155 }
4256
4357 return pairs ;
4458 }
4559
46- public static void main (String [] args ) {
60+ public
61+ static void main (String [] args ) {
4762 int [] array = {1 , 2 , 3 , 4 };
4863 List <int []> pairs = pairShuffle (array );
4964
0 commit comments