package ca.recrown.islandsurvivalcraft.utilities.weighting;

import java.util.Random;
import java.util.TreeMap;

public class WeightedSelector<T extends Weightable> {
    private final TreeMap<Float, T> map;
    private final float totalWeights;

    public WeightedSelector(Iterable<T> set) {
        float totalWeights = 0;
        map = new TreeMap<>();
        for (T t : set) {
            totalWeights += t.getWeight();
            map.put(totalWeights, t);
        }
        this.totalWeights = totalWeights;
    }

    public T selectRandom(Random random) {
        return map.ceilingEntry(random.nextFloat() * totalWeights).getValue();
    }

    public T selectRandom(float selector) {
        return map.ceilingEntry(selector * totalWeights).getValue();
    }
}