Last active
January 26, 2018 17:11
-
-
Save philmadden83/7a47cc911716fb799246885e283f65bd to your computer and use it in GitHub Desktop.
Example of using a Comparator to shuffle elements in an array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} | |
} |
Author
philmadden83
commented
Jan 26, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment