2
2
3
3
import java .util .ArrayList ;
4
4
import java .util .Collections ;
5
+ import java .util .HashSet ;
5
6
import java .util .List ;
7
+ import java .util .Set ;
6
8
7
- public final class UniquePairShuffle {
9
+ public
10
+ final class UniquePairShuffle {
8
11
9
- private UniquePairShuffle () {
12
+ private
13
+ UniquePairShuffle () {
10
14
// Prevent instantiation
11
15
}
12
16
@@ -19,7 +23,8 @@ private UniquePairShuffle() {
19
23
* @return a list of unique pairs where each pair is represented as an integer
20
24
* array of length 2
21
25
*/
22
- public static List <int []> pairShuffle (int [] array ) {
26
+ public
27
+ static List <int []> pairShuffle (int [] array ) {
23
28
List <int []> pairs = new ArrayList <>();
24
29
25
30
// Handle edge case: If the array length is odd, pairing is not possible
@@ -35,15 +40,25 @@ public static List<int[]> pairShuffle(int[] array) {
35
40
// Shuffle elements to create random pairs
36
41
Collections .shuffle (shuffledList );
37
42
38
- // Form pairs from the shuffled elements
43
+ // Form pairs from the shuffled elements, avoiding duplicate pairs
44
+ Set <String > uniquePairs = new HashSet <>();
39
45
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
+ }
41
55
}
42
56
43
57
return pairs ;
44
58
}
45
59
46
- public static void main (String [] args ) {
60
+ public
61
+ static void main (String [] args ) {
47
62
int [] array = {1 , 2 , 3 , 4 };
48
63
List <int []> pairs = pairShuffle (array );
49
64
0 commit comments