Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ShuffleAlgorithm and various problems related to it. #6053

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.thealgorithms.shufflealgo;

import java.util.Arrays;
import java.util.Random;

public
final class ConstrainedShuffle {

private
ConstrainedShuffle() {
// Prevent instantiation
}

/**
* Shuffles elements in the array while ensuring that the first and last
* elements remain fixed.
*
* @param array the input array to shuffle
*/
public
static void constrainedShuffle(int[] array) {
// Edge case: If the array has less than 3 elements, no shuffling can occur
if (array == null || array.length < 3) {
return;
}

Random random = new Random();
// Start loop from the second last element and exclude the first and last
// elements
for (int i = array.length - 2; i > 1; i--) {
// Generate a random index between 1 and i (inclusive)
int j = random.nextInt(i - 1) + 1;

// Swap the elements at positions i and j
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}

public
static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println("Original Array: " + Arrays.toString(array));
constrainedShuffle(array);
System.out.println("Constrained Shuffled Array: " + Arrays.toString(array));
}
}
57 changes: 57 additions & 0 deletions src/main/java/com/thealgorithms/shufflealgo/GroupShuffle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.thealgorithms.shufflealgo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public
final class GroupShuffle {

private
GroupShuffle() {
// Prevent instantiation
}

/**
* Groups and shuffles elements in the array.
*
* @param array the input array to shuffle
* @param groupSize the size of each group
* @return a list of shuffled groups
*/
public
static List<List<Integer>> groupShuffle(int[] array, int groupSize) {
List<List<Integer>> groups = new ArrayList<>();

// Edge case: Check if the group size is valid
if (array == null || groupSize <= 0) {
return groups;
}

for (int i = 0; i < array.length; i += groupSize) {
List<Integer> group = new ArrayList<>();
for (int j = i; j < Math.min(i + groupSize, array.length); j++) {
group.add(array[j]);
}
groups.add(group);
}

// Shuffle only if the group size is greater than 1
if (groupSize > 1) {
Collections.shuffle(groups);
}

return groups;
}

public
static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
List<List<Integer>> shuffledGroups = groupShuffle(array, 3);

System.out.println("Shuffled Groups:");
for (List<Integer> group : shuffledGroups) {
System.out.println(group);
}
}
}
52 changes: 52 additions & 0 deletions src/main/java/com/thealgorithms/shufflealgo/ShuffleByRange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.thealgorithms.shufflealgo;

import java.util.Random;

public
final class ShuffleByRange {

private
ShuffleByRange() {
// Prevent instantiation
}

/**
* Shuffles elements in the specified range of the array.
*
* @param array the input array to shuffle
* @param start the starting index of the range (inclusive)
* @param end the ending index of the range (exclusive)
*/
public
static void shuffleByRange(int[] array, int start, int end) {
// Edge case: Check if the range is valid
if (array == null || start < 0 || end > array.length || start >= end) {
return;
}

Random random = new Random();
for (int i = end - 1; i > start; i--) {
int j = random.nextInt(i - start + 1) + start;

// Swap the elements at positions i and j
int temp = array[i]; // Temporarily store the element at i
array[i] = array[j]; // Move element from j to i
array[j] = temp; // Place the stored element in position j
}
}

public
static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6};
System.out.println("Original Array: ");
for (int num : array) {
System.out.print(num + " ");
}

shuffleByRange(array, 1, 5);
System.out.println("\nShuffled Array (Range 1 to 5): ");
for (int num : array) {
System.out.print(num + " ");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.thealgorithms.shufflealgo;

import java.util.Random;

public
final class UnderstandingShuffleAlgo {

private
UnderstandingShuffleAlgo() {
// Prevent instantiation
}

/**
* Shuffles the elements in the array randomly.
* Uses a method that gives each item an equal chance to appear in any
* position.
*
* @param array the array to be shuffled
*/
public
static void shuffle(int[] array) {
// Create a Random object to generate random numbers
Random random = new Random();

// Loop from the last element to the second element
for (int i = array.length - 1; i > 0; i--) {
// Generate a random index from 0 to i (inclusive)
int j = random.nextInt(i + 1);

// Swap the elements at positions i and j
int temp = array[i]; // Temporarily store the element at i
array[i] = array[j]; // Move element from j to i
array[j] = temp; // Place the stored element in position j
}
}

/**
* Main method to demonstrate the shuffle function.
* Shows the array before and after shuffling.
*
* @param args command-line arguments (not used here)
*/
public
static void main(String[] args) {
// Create an example array of numbers from 1 to 9
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};

// Display the original array
System.out.println("Original Array:");
for (int num : array) {
System.out.print(num + " ");
}

// Call the shuffle method to randomize the array
shuffle(array);

// Display the shuffled array
System.out.println("\nShuffled Array:");
for (int num : array) {
System.out.print(num + " ");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.thealgorithms.shufflealgo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public
final class UniquePairShuffle {

private
UniquePairShuffle() {
// Prevent instantiation
}

/**
* Pairs each element in the array with another element randomly, ensuring no
* pair repeats. If the array length is odd, pairing cannot be completed, so
* an empty list is returned.
*
* @param array the input array to pair elements from
* @return a list of unique pairs where each pair is represented as an integer
* array of length 2
*/
public
static List<int[]> pairShuffle(int[] array) {
List<int[]> pairs = new ArrayList<>();

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

List<Integer> shuffledList = new ArrayList<>();
for (int num : array) {
shuffledList.add(num);
}

// Shuffle elements to create random pairs
Collections.shuffle(shuffledList);

// Form pairs from the shuffled elements
for (int i = 0; i < shuffledList.size(); i += 2) {
pairs.add(new int[]{shuffledList.get(i), shuffledList.get(i + 1)});
}

return pairs;
}

public
static void main(String[] args) {
int[] array = {1, 2, 3, 4};
List<int[]> pairs = pairShuffle(array);

System.out.println("Generated Unique Pairs:");
for (int[] pair : pairs) {
System.out.println(pair[0] + " - " + pair[1]);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.thealgorithms.shufflealgo;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

public
final class WeightedShuffle {

private
WeightedShuffle() {
// Prevent instantiation
}

/**
* Shuffles elements based on their weights. Higher weight elements are more
* likely to appear earlier.
*
* @param array the input array to shuffle
* @param weights the weights for each corresponding element in the array
*/
public
static void weightedShuffle(int[] array, int[] weights) {
// Edge case: Check if weights match the array size
if (array == null || weights == null || array.length != weights.length) {
return;
}

Integer[] indices = new Integer[array.length];
for (int i = 0; i < array.length; i++) {
indices[i] = i;
}

Random random = new Random();

// Sort indices by weights in descending order, prioritizing higher weights
Arrays.sort(indices, Comparator.comparingInt((Integer i)->- weights[i])
.thenComparingInt(i->random.nextInt()));

int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[indices[i]];
}

System.arraycopy(result, 0, array, 0, array.length);
}

public
static void main(String[] args) {
int[] array = {10, 20, 30};
int[] weights = {1, 3, 2};
weightedShuffle(array, weights);

System.out.println("Weighted Shuffled Array:");
for (int num : array) {
System.out.print(num + " ");
}
}
}

Loading
Loading