All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.parzivail.util.generics.RandomCollection Maven / Gradle / Ivy

package com.parzivail.util.generics;

import D;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;

public class RandomCollection
{
	private final NavigableMap map = new TreeMap<>();
	private final Random random;
	private double total = 0;

	public RandomCollection(Random random)
	{
		this.random = random;
	}

	public RandomCollection add(double weight, T result)
	{
		if (weight <= 0)
			return this;
		total += weight;
		map.put(total, result);
		return this;
	}

	public T sample()
	{
		var value = random.nextDouble() * total;
		return map.higherEntry(value).getValue();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy