Skip to content

Instantly share code, notes, and snippets.

@Razeeman
Last active January 30, 2019 13:39
Show Gist options
  • Save Razeeman/59e3796fb1a8c6c6aaf3305e174fc814 to your computer and use it in GitHub Desktop.
Save Razeeman/59e3796fb1a8c6c6aaf3305e174fc814 to your computer and use it in GitHub Desktop.
Get N random elements from list without shuffling whole list.
public class Main {
/**
* Returns new list of N random elements from provided list.
*
* @param list list of elements to choose from
* @param n number of elements to choose
* @param <E> type of elements in a list
* @return new list of N random elements from provided list
*/
public static <E> List<E> getNRandomElementsFromList(List<E> list, int n) {
int listLength = list.size();
Random r = new Random();
if (n >= listLength) return list;
// Collections.shuffle algorithm (Fisher-Yates shuffle) that is stopped
// after acquiring needed number of random elements
for (int i = listLength; i > listLength - n; i--)
Collections.swap(list, i - 1, r.nextInt(i));
return list.subList(listLength - n, listLength);
}
private static void print(float[] array) {
for (float i: array) System.out.print(i + " ");
System.out.print("\n");
}
// Driver code to test probability of each element to appear in results.
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
List<Integer> nRandom = new ArrayList<>();
float[] results = new float[10];
int runs = 1000000;
for (int i = 0; i < runs; i++) {
nRandom = getNRandomElementsFromList(arrayList, 5);
for (int e: nRandom) results[e]++;
}
for (int i = 0; i < results.length; i++) results[i] /= runs;
print(results);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment