在做游戏的时候,我们通常会碰到概率问题,例如奖池道具掉落概率,这时候可以用红黑树来进行解决。
像这个例子:
public class NewTest { public static void main(String[] args) { SortedMap<Integer, String> weightMap = new TreeMap<>(); int totalWeight = 0; /** * 假设概率如下 : * a - 0.1 * b - 0.2 * c - 0.1 * d - 0.4 * e - 0.2 */ totalWeight = 10; weightMap.put(totalWeight, "a"); totalWeight += 20; weightMap.put(totalWeight, "b"); totalWeight += 10; weightMap.put(totalWeight, "c"); totalWeight += 40; weightMap.put(totalWeight, "d"); totalWeight += 20; weightMap.put(totalWeight, "e"); Map<String, Integer> map = new HashMap<>(); Random random = new Random(); for (int i = 0; i <