/* * Decompiled with CFR 0.152. */ package net.minecraft.util.random; import java.util.List; import java.util.Optional; import java.util.function.ToIntFunction; import net.minecraft.util.RandomSource; import net.minecraft.util.Util; public class WeightedRandom { private WeightedRandom() { } public static int getTotalWeight(List items, ToIntFunction weightGetter) { long totalWeight = 0L; for (T item : items) { totalWeight += (long)weightGetter.applyAsInt(item); } if (totalWeight > Integer.MAX_VALUE) { throw new IllegalArgumentException("Sum of weights must be <= 2147483647"); } return (int)totalWeight; } public static Optional getRandomItem(RandomSource random, List items, int totalWeight, ToIntFunction weightGetter) { if (totalWeight < 0) { throw Util.pauseInIde(new IllegalArgumentException("Negative total weight in getRandomItem")); } if (totalWeight == 0) { return Optional.empty(); } int selection = random.nextInt(totalWeight); return WeightedRandom.getWeightedItem(items, selection, weightGetter); } public static Optional getWeightedItem(List items, int index, ToIntFunction weightGetter) { for (T item : items) { if ((index -= weightGetter.applyAsInt(item)) >= 0) continue; return Optional.of(item); } return Optional.empty(); } public static Optional getRandomItem(RandomSource random, List items, ToIntFunction weightGetter) { return WeightedRandom.getRandomItem(random, items, WeightedRandom.getTotalWeight(items, weightGetter), weightGetter); } }