Last active
August 10, 2016 01:52
-
-
Save ghostflare76/fbfa61baba0e59197c7051d3a0287ee7 to your computer and use it in GitHub Desktop.
Weighted Random
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
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