package net.minecraft.util.random; import java.util.List; import java.util.Optional; import java.util.function.ToIntFunction; import net.minecraft.Util; import net.minecraft.util.RandomSource; public class WeightedRandom { private WeightedRandom() { } public static int getTotalWeight(List elements, ToIntFunction weightGetter) { long l = 0L; for (T object : elements) { l += weightGetter.applyAsInt(object); } if (l > 2147483647L) { throw new IllegalArgumentException("Sum of weights must be <= 2147483647"); } else { return (int)l; } } public static Optional getRandomItem(RandomSource random, List elements, int totalWeight, ToIntFunction weightGetter) { if (totalWeight < 0) { throw (IllegalArgumentException)Util.pauseInIde((T)(new IllegalArgumentException("Negative total weight in getRandomItem"))); } else if (totalWeight == 0) { return Optional.empty(); } else { int i = random.nextInt(totalWeight); return getWeightedItem(elements, i, weightGetter); } } public static Optional getWeightedItem(List elements, int index, ToIntFunction weightGetter) { for (T object : elements) { index -= weightGetter.applyAsInt(object); if (index < 0) { return Optional.of(object); } } return Optional.empty(); } public static Optional getRandomItem(RandomSource random, List elements, ToIntFunction weightGetter) { return getRandomItem(random, elements, getTotalWeight(elements, weightGetter), weightGetter); } }