Skip to content

Instantly share code, notes, and snippets.

@hypirion
Created April 11, 2017 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hypirion/467887f0afd8f335b0d00a034e709d0d to your computer and use it in GitHub Desktop.
Save hypirion/467887f0afd8f335b0d00a034e709d0d to your computer and use it in GitHub Desktop.
Collection with constant time insertion (amortised) and constant time uniform random removal
import java.util.*;
public class RandomColl<T> {
ArrayList<T> lst;
Random rng;
public RandomColl() {
lst = new ArrayList<>();
rng = new Random();
}
public void add(T elem) {
lst.add(elem);
}
public T remove() {
if (lst.size() == 0) {
throw new NoSuchElementException();
}
int elemIdx = rng.nextInt(lst.size());
T last = lst.remove(lst.size() - 1);
if (lst.size() == elemIdx) {
return last;
} else {
T elem = lst.get(elemIdx);
lst.set(elemIdx, last);
return elem;
}
}
// sample usage
public static void main(String[] args) {
RandomColl<Integer> rc = new RandomColl<>();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
rc.add(i*10 + j);
}
for (int j = 0; j < 5; j++) {
System.out.println(rc.remove());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment