fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. enum Type {
  6. Normal(10), Rare(2), Yoba(1);
  7.  
  8. int coefficient;
  9. Type(int coefficient) { this.coefficient = coefficient; }
  10. }
  11.  
  12. static class Item {
  13. String name;
  14. int weight;
  15. Type type;
  16. double expectedProbability;
  17.  
  18. public Item(String name, int weight, Type type, double expectedProbability) {
  19. this.name = name;
  20. this.weight = weight;
  21. this.type = type;
  22. this.expectedProbability = expectedProbability;
  23. }
  24.  
  25. @Override
  26. public String toString() { return name; }
  27. }
  28.  
  29. static class WeightedItemSelector {
  30. private final NavigableMap<Integer, Item> map = new TreeMap<>();
  31. private final Random random = new Random();
  32. private final int maxRange;
  33.  
  34. public WeightedItemSelector(Item... items) {
  35. int currentWeight = 0;
  36. for (Item item : items) {
  37. currentWeight += item.weight * item.type.coefficient;
  38. map.put(currentWeight, item);
  39. }
  40. maxRange = currentWeight;
  41. }
  42.  
  43. public Item getNext() {
  44. return map.higherEntry(random.nextInt(maxRange)).getValue();
  45. }
  46. }
  47.  
  48.  
  49.  
  50. private static int iterCount = 1000000;
  51.  
  52. public static void main(String[] args) {
  53. WeightedItemSelector selector = new WeightedItemSelector(
  54. new Item("Шапка пиздоглазия", 5, Type.Normal, 50 / 207d),
  55. new Item("Зелье упоротости", 7, Type.Normal, 70 / 207d),
  56. new Item("Картонный щит", 6, Type.Normal, 60 / 207d),
  57. new Item("Меч-опиздюливатель", 5, Type.Rare, 10 / 207d),
  58. new Item("Шлем из мамкиной кастрюли", 8, Type.Rare, 16 / 207d),
  59. new Item("Хуй дракона", 1, Type.Yoba, 1 / 207d)
  60. );
  61.  
  62. Map<Item, Integer> counters = new HashMap<>();
  63. for (int i = 0; i < iterCount; i++) {
  64. counters.compute(selector.getNext(), (k, v) -> v == null ? 1 : v + 1);
  65. }
  66.  
  67. counters.entrySet().forEach(e -> System.out.println(String.format("%s: expected %f, actual %f", e.getKey().name, e.getKey().expectedProbability, e.getValue().doubleValue() / iterCount)));
  68.  
  69. }
  70.  
  71. }
  72.  
Success #stdin #stdout 0.41s 320832KB
stdin
Standard input is empty
stdout
Шлем из мамкиной кастрюли: expected 0.077295, actual 0.077184
Шапка пиздоглазия: expected 0.241546, actual 0.241527
Картонный щит: expected 0.289855, actual 0.290087
Хуй дракона: expected 0.004831, actual 0.004707
Зелье упоротости: expected 0.338164, actual 0.338564
Меч-опиздюливатель: expected 0.048309, actual 0.047931