WeightedRandom .java

net.minecraft.util.WeightedRandom (class, 66 lines): members: getTotalWeight, getRandomItem, Item.

net.minecraft.utilclass66 linescommon1.5 KB

API Surface (4)

int getTotalWeight(Collection <? extends WeightedRandom.Item > collection)
<T extends WeightedRandom.Item> T getRandomItem(Random random, Collection<T> collection, int totalWeight)
<T extends WeightedRandom.Item> T getRandomItem(Collection<T> collection, int weight)
<T extends WeightedRandom.Item> T getRandomItem(Random random, Collection<T> collection)

Full Source

WeightedRandom.java66 lines · MCP 1.8.9 · verbatimOriginal ↗
1
package net.minecraft.util;
2
3
import java.util.Collection;
4
import java.util.Random;
5
6
public class WeightedRandom
7
{
8
    /**
9
     * Returns the total weight of all items in a collection.
10
     */
11
    public static int getTotalWeight(Collection <? extends WeightedRandom.Item > collection)
12
    {
13
        int i = 0;
14
15
        for (WeightedRandom.Item weightedrandom$item : collection)
16
        {
17
            i += weightedrandom$item.itemWeight;
18
        }
19
20
        return i;
21
    }
22
23
    public static <T extends WeightedRandom.Item> T getRandomItem(Random random, Collection<T> collection, int totalWeight)
24
    {
25
        if (totalWeight <= 0)
26
        {
27
            throw new IllegalArgumentException();
28
        }
29
        else
30
        {
31
            int i = random.nextInt(totalWeight);
32
            return getRandomItem(collection, i);
33
        }
34
    }
35
36
    public static <T extends WeightedRandom.Item> T getRandomItem(Collection<T> collection, int weight)
37
    {
38
        for (T t : collection)
39
        {
40
            weight -= t.itemWeight;
41
42
            if (weight < 0)
43
            {
44
                return t;
45
            }
46
        }
47
48
        return (T)null;
49
    }
50
51
    public static <T extends WeightedRandom.Item> T getRandomItem(Random random, Collection<T> collection)
52
    {
53
        return getRandomItem(random, collection, getTotalWeight(collection));
54
    }
55
56
    public static class Item
57
    {
58
        protected int itemWeight;
59
60
        public Item(int itemWeightIn)
61
        {
62
            this.itemWeight = itemWeightIn;
63
        }
64
    }
65
}
66

Deobfuscated MCP 1.8.9 source of WeightedRandom from Marcelektro/MavenMCP-1.8.9 (net/minecraft/util/WeightedRandom.java), stored verbatim.