Skip to content

Commit f43c5de

Browse files
added shuffle algorithms, it's implementation and problem related to it
1 parent a163816 commit f43c5de

File tree

6 files changed

+278
-0
lines changed

6 files changed

+278
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms.shufflealogrithm;
2+
3+
import java.util.Collections;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
7+
public class ConstrainedShuffle {
8+
9+
/**
10+
* Shuffles the array so that no element stays in its original position.
11+
*
12+
* @param array the input array to shuffle with constraints
13+
*/
14+
public static void constrainedShuffle(int[] array) {
15+
// Edge case: Check if array has only one element (no valid shuffle possible)
16+
if (array == null || array.length <= 1) return;
17+
18+
List<Integer> shuffledList = new ArrayList<>();
19+
for (int num : array) shuffledList.add(num);
20+
21+
do {
22+
Collections.shuffle(shuffledList);
23+
} while (!isValidShuffle(array, shuffledList));
24+
25+
for (int i = 0; i < array.length; i++) array[i] = shuffledList.get(i);
26+
}
27+
28+
/**
29+
* Verifies that no element is in its original position in the shuffled list.
30+
*/
31+
private static boolean isValidShuffle(int[] original, List<Integer> shuffled) {
32+
for (int i = 0; i < original.length; i++) {
33+
if (original[i] == shuffled.get(i)) return false;
34+
}
35+
return true;
36+
}
37+
38+
public static void main(String[] args) {
39+
int[] array = {1, 2, 3, 4};
40+
constrainedShuffle(array);
41+
42+
System.out.println("Constrained Shuffled Array:");
43+
for (int num : array) {
44+
System.out.print(num + " ");
45+
}
46+
}
47+
}
48+
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.thealgorithms.shufflealogrithm;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
public class GroupShuffle {
8+
9+
/**
10+
* Divides the array into k equal-sized groups and shuffles each group separately.
11+
* Returns an empty list if the group count exceeds the array length.
12+
*
13+
* @param array the input array to split into groups
14+
* @param k the number of groups to create
15+
* @return a list of groups, where each group is a shuffled sublist of the input array
16+
*/
17+
public static List<List<Integer>> groupShuffle(int[] array, int k) {
18+
List<List<Integer>> groups = new ArrayList<>();
19+
20+
// Edge case: Check if grouping is possible
21+
if (k > array.length || k <= 0) return groups;
22+
23+
List<Integer> shuffledList = new ArrayList<>();
24+
for (int num : array) shuffledList.add(num);
25+
Collections.shuffle(shuffledList);
26+
27+
int groupSize = array.length / k;
28+
int remainder = array.length % k;
29+
30+
// Distribute elements into k groups
31+
for (int i = 0; i < k; i++) {
32+
int end = (i + 1) * groupSize + (i < remainder ? 1 : 0);
33+
groups.add(new ArrayList<>(shuffledList.subList(i * groupSize + Math.min(i, remainder), end)));
34+
}
35+
36+
return groups;
37+
}
38+
39+
public static void main(String[] args) {
40+
int[] array = {1, 2, 3, 4, 5, 6};
41+
int k = 3;
42+
List<List<Integer>> groups = groupShuffle(array, k);
43+
44+
System.out.println("Shuffled Groups:");
45+
for (List<Integer> group : groups) {
46+
System.out.println(group);
47+
}
48+
}
49+
}
50+
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.thealgorithms.shufflealogrithm;
2+
3+
import java.util.Random;
4+
5+
public class ShuffleByRange {
6+
7+
/**
8+
* Shuffles elements within a specified index range, leaving elements outside this range unchanged.
9+
*
10+
* @param array the input array to shuffle
11+
* @param start starting index of the range to shuffle
12+
* @param end ending index of the range to shuffle
13+
*/
14+
public static void shuffleRange(int[] array, int start, int end) {
15+
// Edge case handling
16+
if (array == null || start < 0 || end >= array.length || start >= end) return;
17+
18+
Random random = new Random();
19+
20+
// Shuffle elements only in the specified range
21+
for (int i = end; i > start; i--) {
22+
int j = start + random.nextInt(i - start + 1);
23+
int temp = array[i];
24+
array[i] = array[j];
25+
array[j] = temp;
26+
}
27+
}
28+
29+
public static void main(String[] args) {
30+
int[] array = {10, 20, 30, 40, 50, 60};
31+
int start = 1;
32+
int end = 4;
33+
shuffleRange(array, start, end);
34+
35+
System.out.println("Array after shuffling range:");
36+
for (int num : array) {
37+
System.out.print(num + " ");
38+
}
39+
}
40+
}
41+
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.thealgorithms.shufflealogrithm;
2+
3+
import java.util.Random;
4+
5+
public class UnderstandingShuffleAlgo {
6+
7+
/**
8+
* Shuffles the elements in the array randomly.
9+
* Uses a method that gives each item an equal chance to appear in any position.
10+
*
11+
* @param array the array to be shuffled
12+
*/
13+
public static void shuffle(int[] array) {
14+
// Create a Random object to generate random numbers
15+
Random random = new Random();
16+
17+
// Loop from the last element to the second element
18+
for (int i = array.length - 1; i > 0; i--) {
19+
// Generate a random index from 0 to i (inclusive)
20+
int j = random.nextInt(i + 1);
21+
22+
// Swap the elements at positions i and j
23+
int temp = array[i]; // Temporarily store the element at i
24+
array[i] = array[j]; // Move element from j to i
25+
array[j] = temp; // Place the stored element in position j
26+
}
27+
}
28+
29+
/**
30+
* Main method to demonstrate the shuffle function.
31+
* Shows the array before and after shuffling.
32+
*
33+
* @param args command-line arguments (not used here)
34+
*/
35+
public static void main(String[] args) {
36+
// Create an example array of numbers from 1 to 9
37+
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
38+
39+
// Display the original array
40+
System.out.println("Original Array:");
41+
for (int num : array) {
42+
System.out.print(num + " ");
43+
}
44+
45+
// Call the shuffle method to randomize the array
46+
shuffle(array);
47+
48+
// Display the shuffled array
49+
System.out.println("\nShuffled Array:");
50+
for (int num : array) {
51+
System.out.print(num + " ");
52+
}
53+
}
54+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.thealgorithms.shufflealogrithm;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
public class UniquePairShuffle {
8+
9+
/**
10+
* Pairs each element in the array with another element randomly, ensuring no pair repeats.
11+
* If the array length is odd, pairing cannot be completed, so an empty list is returned.
12+
*
13+
* @param array the input array to pair elements from
14+
* @return a list of unique pairs where each pair is represented as an integer array of length 2
15+
*/
16+
public static List<int[]> pairShuffle(int[] array) {
17+
List<int[]> pairs = new ArrayList<>();
18+
19+
// Handle edge case: If the array length is odd, pairing is not possible
20+
if (array.length % 2 != 0) return pairs;
21+
22+
List<Integer> shuffledList = new ArrayList<>();
23+
for (int num : array) shuffledList.add(num);
24+
25+
// Shuffle elements to create random pairs
26+
Collections.shuffle(shuffledList);
27+
28+
// Form pairs from the shuffled elements
29+
for (int i = 0; i < shuffledList.size(); i += 2) {
30+
pairs.add(new int[]{shuffledList.get(i), shuffledList.get(i + 1)});
31+
}
32+
33+
return pairs;
34+
}
35+
36+
public static void main(String[] args) {
37+
int[] array = {1, 2, 3, 4};
38+
List<int[]> pairs = pairShuffle(array);
39+
40+
System.out.println("Generated Unique Pairs:");
41+
for (int[] pair : pairs) {
42+
System.out.println(pair[0] + " - " + pair[1]);
43+
}
44+
}
45+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.thealgorithms.shufflealogrithm;
2+
3+
import java.util.Arrays;
4+
import java.util.Comparator;
5+
6+
public class WeightedShuffle {
7+
8+
/**
9+
* Shuffles elements based on their weights. Higher weight elements are more likely to appear earlier.
10+
*
11+
* @param array the input array to shuffle
12+
* @param weights the weights for each corresponding element in the array
13+
*/
14+
public static void weightedShuffle(int[] array, int[] weights) {
15+
// Edge case: Check if weights match the array size
16+
if (array == null || weights == null || array.length != weights.length) return;
17+
18+
Integer[] indices = new Integer[array.length];
19+
for (int i = 0; i < array.length; i++) indices[i] = i;
20+
21+
Arrays.sort(indices, Comparator.comparingInt(i -> -weights[i]));
22+
23+
int[] result = new int[array.length];
24+
for (int i = 0; i < array.length; i++) result[i] = array[indices[i]];
25+
26+
System.arraycopy(result, 0, array, 0, array.length);
27+
}
28+
29+
public static void main(String[] args) {
30+
int[] array = {10, 20, 30};
31+
int[] weights = {1, 3, 2};
32+
weightedShuffle(array, weights);
33+
34+
System.out.println("Weighted Shuffled Array:");
35+
for (int num : array) {
36+
System.out.print(num + " ");
37+
}
38+
}
39+
}
40+

0 commit comments

Comments
 (0)