Skip to content

Instantly share code, notes, and snippets.

@philmadden83
Last active January 26, 2018 17:11
Show Gist options
  • Save philmadden83/7a47cc911716fb799246885e283f65bd to your computer and use it in GitHub Desktop.
Save philmadden83/7a47cc911716fb799246885e283f65bd to your computer and use it in GitHub Desktop.
Example of using a Comparator to shuffle elements in an array.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
public final class Shuffler {
private static final RandomComparator RANDOM_COMPARATOR = new RandomComparator();
public static <T> List<T> shuffle(T[] args) {
List<T> argList = Arrays.asList(args);
argList.sort(RANDOM_COMPARATOR);
return argList;
}
private static class RandomComparator implements Comparator {
private final Random RANDOM = new Random();
@Override
public int compare(Object o1, Object o2) {
return getRandomComparison();
}
/**
* Generates an integer in the range of -1 ≥ n ≤ 1
* @return int
*/
private int getRandomComparison() {
return (int) (-1 + (Math.round(RANDOM.nextDouble()) * 2));
}
}
}
@philmadden83
Copy link
Author

Shuffler.shuffle(new String[]  { "one", "two", "three", "four", "five", "six" });
Shuffler.shuffle(new Integer[] { 1, 2, 3, 4, 5, 6});
Shuffler.shuffle(new Float[]   { 1.1F, 2.2F, 3.3F, 4.4F, 5.5F, 6.6F});
[one, two, three, four, five, six]
[3, 4, 6, 1, 2, 5]
[1.1, 2.2, 6.6, 3.3, 5.5, 4.4]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment