Skip to content

Instantly share code, notes, and snippets.

@Amejonah1200
Last active April 25, 2021 17:43
Show Gist options
  • Save Amejonah1200/c9ed4e5e5a9c599ab94d61d01ca9e236 to your computer and use it in GitHub Desktop.
Save Amejonah1200/c9ed4e5e5a9c599ab94d61d01ca9e236 to your computer and use it in GitHub Desktop.
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
public class WeightedRandomEvents<A> {
private final Map<Integer, Consumer<A>> events;
public WeightedRandomEvents(@NotNull Map<Integer, Consumer<A>> events) {
this.events = Objects.requireNonNull(events);
checkSum();
}
public WeightedRandomEvents(@NotNull List<Integer> percentages, @NotNull List<Consumer<A>> events) {
this.events = new HashMap<>();
AtomicInteger i = new AtomicInteger();
percentages.forEach(p -> this.events.put(p, events.get(i.getAndIncrement())));
checkSum();
}
private void checkSum() {
if (events.keySet().stream().mapToInt(value -> value).sum() > 100)
throw new IllegalArgumentException("Sum of percentages must be equal or lower than 100!");
}
public void randomExecute(A input) {
final int randomNumber = ThreadLocalRandom.current().nextInt(100);
int temp = 0;
for (Map.Entry<Integer, Consumer<A>> entry : events.entrySet()) {
if (temp <= randomNumber && randomNumber < temp + entry.getKey()) {
entry.getValue().accept(input);
break;
} else temp += entry.getKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment