2020-07-23 19:29:59 +02:00
|
|
|
package com.baeldung.probability;
|
|
|
|
|
|
|
|
import io.vavr.Lazy;
|
|
|
|
|
|
|
|
import java.util.SplittableRandom;
|
|
|
|
import java.util.function.Supplier;
|
|
|
|
|
|
|
|
public class RandomInvoker {
|
|
|
|
private final Lazy<SplittableRandom> random = Lazy.of(SplittableRandom::new);
|
|
|
|
|
2020-08-06 00:11:13 +02:00
|
|
|
public <T> T withProbability(Supplier<T> positiveCase, Supplier<T> negativeCase, int probability) {
|
2020-07-23 19:29:59 +02:00
|
|
|
SplittableRandom random = this.random.get();
|
|
|
|
if (random.nextInt(1, 101) <= probability) {
|
2020-08-06 00:11:13 +02:00
|
|
|
return positiveCase.get();
|
2020-07-23 19:29:59 +02:00
|
|
|
} else {
|
2020-08-06 00:11:13 +02:00
|
|
|
return negativeCase.get();
|
2020-07-23 19:29:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|