package net.minecraft.util.random; import com.google.common.collect.ImmutableList; import com.mojang.serialization.Codec; import java.util.List; import java.util.Objects; import java.util.Optional; import net.minecraft.util.RandomSource; import org.jetbrains.annotations.Nullable; public class WeightedRandomList { private final int totalWeight; private final ImmutableList items; WeightedRandomList(List items) { this.items = ImmutableList.copyOf(items); this.totalWeight = WeightedRandom.getTotalWeight(items); } public static WeightedRandomList create() { return new WeightedRandomList<>(ImmutableList.of()); } @SafeVarargs public static WeightedRandomList create(E... items) { return new WeightedRandomList<>(ImmutableList.copyOf(items)); } public static WeightedRandomList create(List items) { return new WeightedRandomList<>(items); } public boolean isEmpty() { return this.items.isEmpty(); } public Optional getRandom(RandomSource random) { if (this.totalWeight == 0) { return Optional.empty(); } else { int i = random.nextInt(this.totalWeight); return WeightedRandom.getWeightedItem(this.items, i); } } public List unwrap() { return this.items; } public static Codec> codec(Codec elementCodec) { return elementCodec.listOf().xmap(WeightedRandomList::create, WeightedRandomList::unwrap); } public boolean equals(@Nullable Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { WeightedRandomList weightedRandomList = (WeightedRandomList)object; return this.totalWeight == weightedRandomList.totalWeight && Objects.equals(this.items, weightedRandomList.items); } else { return false; } } public int hashCode() { return Objects.hash(new Object[]{this.totalWeight, this.items}); } }