NullValkyrie

Minecraft 1.19 multipurpose plugin for spigot servers with a lot of features where most modern servers have.
git clone https://codeberg.org/night0721/NullValkyrie
Log | Files | Refs | README | LICENSE

RandomCollection.java (1351B)


      1 package me.night.nullvalkyrie.util;
      2 
      3 import java.util.*;
      4 
      5 public class RandomCollection<E> {
      6 
      7     private final NavigableMap<Double, E> map = new TreeMap<>();
      8     private final HashMap<E, Double> chance = new HashMap<>();
      9     private final Random random = new Random();
     10     private double total = 0;
     11 
     12     public void add(Double weight, E value) {
     13         total += weight;
     14         map.put(total, value);
     15         chance.put(value, weight);
     16     }
     17 
     18     public void remove(E value) {
     19         if (chance.containsKey(value)) {
     20             chance.remove(value);
     21             total = 0;
     22             map.clear();
     23             for (E e : chance.keySet()) {
     24                 total += chance.get(e);
     25                 map.put(total, e);
     26             }
     27         }
     28     }
     29 
     30     public E getRandom() {
     31         if (total == 0) return null;
     32         double value = random.nextDouble() * total;
     33         return map.ceilingEntry(value).getValue();
     34     }
     35 
     36     public long getChance(E v) {
     37         double c = 0;
     38         for (E d : chance.keySet()) {
     39             if (d == v) {
     40                 c = chance.get(d);
     41                 break;
     42             }
     43         }
     44         return Math.round((c / total) * 100);
     45     }
     46     // write a method to get all the values in the collection so you can iterate over them
     47     public List<E> getAll() {
     48         return new ArrayList<>(map.values());
     49     }
     50 }