WeightedRandom .java

net.minecraft.util.random.WeightedRandom (class, 55 lines): members: getWeightedItem, getTotalWeight, getRandomItem. imports: Util.

net.minecraft.util.randomclass55 linescommon1.6 KB

API Surface (4)

<T> int getTotalWeight(final List<T> items, final ToIntFunction<T> weightGetter)
<T> Optional<T> getRandomItem(final RandomSource random, final List<T> items, final int totalWeight, final ToIntFunction<T> weightGetter)
<T> Optional<T> getWeightedItem(final List<T> items, int index, final ToIntFunction<T> weightGetter)
<T> Optional<T> getRandomItem(final RandomSource random, final List<T> items, final ToIntFunction<T> weightGetter)

String literals (2)

"Sum of weights must be <= 2147483647"
"Negative total weight in getRandomItem"

Code Graph: Dependencies (2)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

WeightedRandom.java55 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.util.random;
2
3
import java.util.List;
4
import java.util.Optional;
5
import java.util.function.ToIntFunction;
6
import net.minecraft.util.RandomSource;
7
import net.minecraft.util.Util;
8
9
public class WeightedRandom {
10
	private WeightedRandom() {
11
	}
12
13
	public static <T> int getTotalWeight(final List<T> items, final ToIntFunction<T> weightGetter) {
14
		long totalWeight = 0L;
15
16
		for (T item : items) {
17
			totalWeight += weightGetter.applyAsInt(item);
18
		}
19
20
		if (totalWeight > 2147483647L) {
21
			throw new IllegalArgumentException("Sum of weights must be <= 2147483647");
22
		} else {
23
			return (int)totalWeight;
24
		}
25
	}
26
27
	public static <T> Optional<T> getRandomItem(final RandomSource random, final List<T> items, final int totalWeight, final ToIntFunction<T> weightGetter) {
28
		if (totalWeight < 0) {
29
			throw (IllegalArgumentException)Util.pauseInIde(new IllegalArgumentException("Negative total weight in getRandomItem"));
30
		}
31
32
		if (totalWeight == 0) {
33
			return Optional.empty();
34
		}
35
36
		int selection = random.nextInt(totalWeight);
37
		return getWeightedItem(items, selection, weightGetter);
38
	}
39
40
	public static <T> Optional<T> getWeightedItem(final List<T> items, int index, final ToIntFunction<T> weightGetter) {
41
		for (T item : items) {
42
			index -= weightGetter.applyAsInt(item);
43
			if (index < 0) {
44
				return Optional.of(item);
45
			}
46
		}
47
48
		return Optional.empty();
49
	}
50
51
	public static <T> Optional<T> getRandomItem(final RandomSource random, final List<T> items, final ToIntFunction<T> weightGetter) {
52
		return getRandomItem(random, items, getTotalWeight(items, weightGetter), weightGetter);
53
	}
54
}
55

Decompiled Minecraft 26.3 source of WeightedRandom (net/minecraft/util/random/WeightedRandom.java) with Mojang official mappings, stored verbatim on the site.