Random.Range gives unexpected distribution

Hi all,

I just started a new project and within the first few lines of code there’s already some unexpected behaviour. I create a list of nodes in the following manner:

Node X: 0 - 10 times
Node A: 1 time
Node X: 0 - 10 times
Node B: 1 time
Node X: 0 - 10 times

So, there 3 different kinds of nodes. The list always contains exactly one node of type A and of of type B. Before, in between and after these nodes there is a random amount (capped from 0 to 10, respectively) of nodes of type X. This amount is generated by Random.Range at runtime. The code looks like this:

public void CreateMap()
    {
        nodes.Clear();

        CoinNode coinNode;

        int i, j, k;

        for (i = 0; i < Random.Range(0, 11); i++)
        {
            coinNode = new CoinNode();
            nodes.Add(coinNode);
        }

        StartNode start = new StartNode();
        nodes.Add(start);

        for (j = 0; j < Random.Range(0, 11); j++)
        {
            coinNode = new CoinNode();
            nodes.Add(coinNode);
        }

        GraveyardNode graveyard = new GraveyardNode();
        nodes.Add(graveyard);

        for (k = 0; k < Random.Range(0, 11); k++)
        {
            coinNode = new CoinNode();
            nodes.Add(coinNode);
        }

        Debug.Log($"i: {i}\tj: {j}\tk:{k}");

        Map map = new Map(nodes);
    }

I’ve made 100 runs of this algorithm leading to 300 numbers generated with the following results for the Random.Range function:

0: 25 times
1: 42 times
2: 66 times
3: 56 times
4: 61 times
5: 31 times
6: 13 times
7: 4 times
8: 1 time
9: 1 time
10: 0 times

Now, there must be something off obviously, but I don’t know what. Can anybody help me out here?

Kind regards and thank you in advance!

I mean the most apparent thing I can see is using Random.Range in the for loop itself. That will calculate a random value for every iteration of the loop, which I don’t think is a behaviour you’d want.

Though what distribution are you expecting?

3 Likes

Isolate, isolate, isolate.

Remove ALL of that crazy wild list processing code and make a loop that pumps the random numbers out in a loop, tallying instances of each result.

That way you can be satisfied that the distribution is within reason. Over a sufficiently large run it will be.

If you are still seeing artifacts in your code, then you have a bug. Go fix your bug.

One approach is to make 10000 or whatever Random float numbers, store them in a text file as a giant JSON array, then use them again and again while you debug your code.

This isolate the random source from your code and lets you debug each individual value.

Oh, what an oversight. Didn’t see the forest for the trees there but that for sure solves it. Thank you.