Skip to content

Commit 1493800

Browse files
resolves problems
1 parent 9f38af6 commit 1493800

File tree

2 files changed

+5
-15
lines changed

2 files changed

+5
-15
lines changed

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

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ static List<int[]> pairShuffle(int[] array) {
2828
List<int[]> pairs = new ArrayList<>();
2929

3030
// Handle edge case: If the array length is odd, pairing is not possible
31-
if (array.length % 2 != 0) {
31+
if (array.length < 2 || array.length % 2 != 0) {
3232
return pairs;
3333
}
3434

@@ -40,18 +40,9 @@ static List<int[]> pairShuffle(int[] array) {
4040
// Shuffle elements to create random pairs
4141
Collections.shuffle(shuffledList);
4242

43-
// Form pairs from the shuffled elements, avoiding duplicate pairs
44-
Set<String> uniquePairs = new HashSet<>();
43+
// Form pairs from the shuffled elements
4544
for (int i = 0; i < shuffledList.size(); i += 2) {
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-
}
45+
pairs.add(new int[]{shuffledList.get(i), shuffledList.get(i + 1)});
5546
}
5647

5748
return pairs;

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,8 @@ 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 to break
37-
// ties
38-
Arrays.sort(indices, Comparator.<Integer>comparingInt(i->- weights[i])
36+
// Sort indices by weights in descending order, prioritizing higher weights
37+
Arrays.sort(indices, Comparator.comparingInt((Integer i)->- weights[i])
3938
.thenComparingInt(i->random.nextInt()));
4039

4140
int[] result = new int[array.length];

0 commit comments

Comments
 (0)