Skip to content

Instantly share code, notes, and snippets.

@ghostflare76
Last active August 10, 2016 01:52
Show Gist options
  • Save ghostflare76/fbfa61baba0e59197c7051d3a0287ee7 to your computer and use it in GitHub Desktop.
Save ghostflare76/fbfa61baba0e59197c7051d3a0287ee7 to your computer and use it in GitHub Desktop.
Weighted Random
static class Weighting {
String name;
int weight;
public Weighting(String name, int weight) {
this.name = name;
this.weight = weight;
}
}
public static String weightedRandom(List<Weighting> weightingOptions) {
int total = 0;
for (Weighting w : weightingOptions) {
total += w.weight;
}
int random = ThreadLocalRandom.current().nextInt(total);
int current = 0;
for (Weighting w : weightingOptions) {
current += w.weight;
if (random < current) {
return w.name;
}
}
return null;
}
@Test
public void test() {
List<Weighting> weightings = new ArrayList<Weighting>();
weightings.add(new Weighting("Orange", 40));
weightings.add(new Weighting("Mango", 2));
weightings.add(new Weighting("Lemon", 2));
weightings.add(new Weighting("Apple", 1));
weightings.add(new Weighting("Banana", 1));
for (int i = 0; i < 100; i++) {
System.out.println(weightedRandom(weightings));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment