Created
April 11, 2017 23:03
-
-
Save hypirion/467887f0afd8f335b0d00a034e709d0d to your computer and use it in GitHub Desktop.
Collection with constant time insertion (amortised) and constant time uniform random removal
This file contains 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.*; | |
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