fork(4) download
  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.Random;
  4. import java.util.stream.Collectors;
  5. import java.util.stream.IntStream;
  6.  
  7. class Main
  8. {
  9. static class RandomMethod {
  10. private final Runnable method;
  11. private final int chance;
  12.  
  13. RandomMethod(Runnable method, int chance){
  14. this.method = method;
  15. this.chance = chance;
  16. }
  17.  
  18. public int getChance() { return chance; }
  19. public void run() { method.run(); }
  20. }
  21.  
  22. static class MethodChooser {
  23. private final List<RandomMethod> methods;
  24. private final int total;
  25.  
  26. MethodChooser(final List<RandomMethod> methods) {
  27. this.methods = methods;
  28. this.total = methods.stream().collect(Collectors.summingInt(RandomMethod::getChance));
  29. }
  30.  
  31. public void chooseMethod() {
  32. final Random random = new Random();
  33. final int choice = random.nextInt(total);
  34.  
  35. int count = 0;
  36. for (final RandomMethod method : methods)
  37. {
  38. count += method.getChance();
  39. if (choice < count) {
  40. method.run();
  41. return;
  42. }
  43. }
  44. }
  45. }
  46.  
  47. private static void aaa() { System.out.println("a"); }
  48. private static void bbb() { System.out.println("b"); }
  49. private static void ccc() { System.out.println("c"); }
  50.  
  51. public static void main(String[] args) {
  52. MethodChooser chooser = new MethodChooser(Arrays.asList(
  53. new RandomMethod(Main::aaa, 1),
  54. new RandomMethod(Main::bbb, 3),
  55. new RandomMethod(Main::ccc, 1)
  56. ));
  57.  
  58. IntStream.range(0, 100).forEach(
  59. i -> chooser.chooseMethod()
  60. );
  61. }
  62. }
Success #stdin #stdout 0.16s 4386816KB
stdin
Standard input is empty
stdout
b
b
a
b
a
b
b
b
c
b
a
a
b
b
a
b
a
b
b
b
c
c
b
c
c
c
b
b
b
b
a
b
c
b
c
b
a
b
b
c
b
a
b
c
b
a
b
c
b
a
b
b
a
a
a
a
c
b
c
b
a
b
b
b
b
c
c
b
c
b
b
c
b
c
c
b
c
a
b
c
a
b
b
a
b
a
b
a
c
b
c
b
b
b
b
b
b
b
a
b