001/* 002 * PlotSquared, a land and world management plugin for Minecraft. 003 * Copyright (C) IntellectualSites <https://intellectualsites.com> 004 * Copyright (C) IntellectualSites team and contributors 005 * 006 * This program is free software: you can redistribute it and/or modify 007 * it under the terms of the GNU General Public License as published by 008 * the Free Software Foundation, either version 3 of the License, or 009 * (at your option) any later version. 010 * 011 * This program is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014 * GNU General Public License for more details. 015 * 016 * You should have received a copy of the GNU General Public License 017 * along with this program. If not, see <https://www.gnu.org/licenses/>. 018 */ 019package com.plotsquared.core.collection; 020 021import java.util.Map; 022import java.util.NavigableMap; 023import java.util.Random; 024import java.util.TreeMap; 025 026public class SimpleRandomCollection<E> extends RandomCollection<E> { 027 028 private final NavigableMap<Double, E> map = new TreeMap<>(); 029 private double total = 0; 030 031 public SimpleRandomCollection(Map<E, Double> weights, Random random) { 032 super(weights, random); 033 for (Map.Entry<E, Double> entry : weights.entrySet()) { 034 add(entry.getValue(), entry.getKey()); 035 } 036 } 037 038 public void add(double weight, E result) { 039 if (weight <= 0) { 040 return; 041 } 042 total += weight; 043 map.put(total, result); 044 } 045 046 public E next() { 047 return map.ceilingEntry(random.nextDouble()).getValue(); 048 } 049 050}