Skip to content

Commit 9f38af6

Browse files
resolved errors
1 parent 545aeae commit 9f38af6

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

src/main/java/com/thealgorithms/shufflealogrithm/UniquePairShuffle.java

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@
22

33
import java.util.ArrayList;
44
import java.util.Collections;
5+
import java.util.HashSet;
56
import 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

src/main/java/com/thealgorithms/shufflealogrithm/WeightedShuffle.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ static void weightedShuffle(int[] array, int[] weights) {
3333

3434
Random random = new Random();
3535

36-
// Sort indices by weights in descending order, with a random factor for
36+
// Sort indices by weights in descending order with a random factor to break
3737
// ties
3838
Arrays.sort(indices, Comparator.<Integer>comparingInt(i->- weights[i])
3939
.thenComparingInt(i->random.nextInt()));

0 commit comments

Comments
 (0)