minecraft-src/net/minecraft/util/random/WeightedRandomList.java
2025-07-04 01:41:11 +03:00

68 lines
2 KiB
Java

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<E extends WeightedEntry> {
private final int totalWeight;
private final ImmutableList<E> items;
WeightedRandomList(List<? extends E> items) {
this.items = ImmutableList.copyOf(items);
this.totalWeight = WeightedRandom.getTotalWeight(items);
}
public static <E extends WeightedEntry> WeightedRandomList<E> create() {
return new WeightedRandomList<>(ImmutableList.of());
}
@SafeVarargs
public static <E extends WeightedEntry> WeightedRandomList<E> create(E... items) {
return new WeightedRandomList<>(ImmutableList.copyOf(items));
}
public static <E extends WeightedEntry> WeightedRandomList<E> create(List<E> items) {
return new WeightedRandomList<>(items);
}
public boolean isEmpty() {
return this.items.isEmpty();
}
public Optional<E> 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<E> unwrap() {
return this.items;
}
public static <E extends WeightedEntry> Codec<WeightedRandomList<E>> codec(Codec<E> 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});
}
}