MV Distribute a value randomly among an array but with limit

I'm trying to create a function within my plugin to distribute a given numeric value among an array with variable length.
In addition, each array element may not exceed a given limit.

This is for my MV project, however the function itself has nothing to do with the engine, hence why I posted this thread in "Learning Javascript".



So, as an example of what I want to accomplish:

Let's say you have the value 100 and want to distribute that in an array with 3 elements and a limit of 50.

I would expect results like this:

arr = [25,30,45];
arr = [31,28,41];
arr = [18,50,32];



I already created a kind of primitive function for this:

JavaScript:
function distributeNumbers(value,length,limit=0) {
    var numbersList = {};
    
    for (let i = length; i > 0; i--) {
        numbersList[i] = 0;
    };
    
    for (let i = value; i > 0; i--) {
        var pick = rnd_num(1,length);                        //check note below
        if (limit == 0 || numbersList[pick] < limit) {numbersList[pick] += 1;} else {i += 1;}
    };
    
    return numbersList;
};

Note: the rnd_num() function just takes two numeric values and returns a random number ranging from the lower number to the higher number, including themselves.

This works well enough for what it's supposed to do, but the way the numbers are distributed, it's way too evenly divided.
No wonder, since each array element effectively has the same odds of increasing by one.

so instead I'm getting results like these:

arr = [33,30,37];
arr = [31,31,38];
arr = [32,35,33];



Any recommendations are welcome!
I have a couple of ideas, but question first: what would you want to do if the argument for limit is a value where even if every element is the max it can be it won't add up to value? Like say distributeNumbers(500, 3, 50)
@Trihan
Valid question, but that should not be possible in the way I want to use this function. For the time being, all instances of this function are supposed to have parameters exclusively defined by me.

But for all intents and purposes, I think it should be fine if all elements just get 'maxed out' to the limit and the remaining value is discarded.
@Trihan
Valid question, but that should not be possible in the way I want to use this function. For the time being, all instances of this function are supposed to have parameters exclusively defined by me.

But for all intents and purposes, I think it should be fine if all elements just get 'maxed out' to the limit and the remaining value is discarded.
Could it be like [50, 50, 0] or do all elements need at least 1?
@Trihan
I currently can't think of a reason why it couldn't be 0.
So I doubt there is a need for a minimum, but then again, it might be nice to have a variant with a minimum for future reference. Only if it's not too much effort of course.
An issue I see with this loop:
JavaScript:
for (let i = value; i > 0; i--) {
    var pick = rnd_num(1,length);                        //check note below
    if (limit == 0 || numbersList[pick] < limit) {numbersList[pick] += 1;} else {i += 1;}
};

Is that var pick = rnd_num(1,length); could technically never pick one of the array elements (probably not going to happen if these arrays are short.)

Also, that loop has to run a minimum of value times where it could be more depending on what rnd_num picks.

Edit: I've just noticed my solution doesn't take the limit into consideration for the last element :asad:
I think my earlier points should be considered but this below solution doesn't work when a limit is involved 🙁


Edit: Found a solution to that ^ although it's a biiiiiit ugly, I'll try and write an explanation for it later...

Spoiler: Solution?
It seems that value is going to be greater than length so it would be better to loop with the length of the array. I tried this:
JavaScript:
function distributeNumbers (value, length, limit = value + 1) {
    let arr = [];
 
    // e.g. loops from element[0] -> element[1] if length = 3
    for (let i = 0; i < length-1; i++) {
   
        // this line calculates what is the smallest possible value allowed based on the remaining value and limit.
        let minAllowed = limit > value ? 0 : Math.max(0, value - (limit * (length - (i + 1))));
        arr[i] = rnd_num(minAllowed, Math.min(value, limit));
        value -= arr[i];
    }

    // last element takes remaining value
    // e.g. element[2] if length = 3
    arr[length-1] = value;

    // SHUFFLE ARRAY HERE
    console.log(arr);
};

This will go through each element of the array and assign a random number to it between minAllowed and either value or limit (whichever is smaller.) if there's no limit, limit defaults to a number higher than value and won't be used for the rnd_num.

When the random element is chosen, it's taken away from the total so the next element will choose between 0 and (value - previousElement.)

The last element will always take what is remaining of the value

e.g.
value = 100
el[0] = 0 <-> 100 = 67
el[1] = 0 <-> 33 = 10
el [2] = automatically becomes 23

One caveat with this method is that you'll want to shuffle the array afterwards. Easy to do if the array length is small (https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) some good suggestions here, I went with, for this example:

JavaScript:
for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
}

return array;

This way the distribution is always O(2n), loops the entire array for randomizing and then again for shuffling. This should be quicker than looping through as many times as value (which I assume could be in the hundreds?)

Another caveat is that larger arrays will tend to have a higher frequency of lower numbers, when there is no limit, as the first few elements could be anywhere from 0 to value. Guess this does not help you if you wanted a more even distribution...
Sorry for the late reply.

@NotADev
Thank you very much, that is a great start.

But even though there is some variance between the numbers, there are some repeating trends happening.

For example when I ran
JavaScript:
distributeNumbers(300,3,125)
5 times, I got these results:
JavaScript:
[101, 115, 84]
[91, 119, 100]
[121, 101, 78]
[58, 123, 119]
[92, 111, 97]


So there is often one value in the 110 - 120 range and one value in the 80-100 range with the remaining value taking the rest.

However, this method *should* still suffice for now. So thank you again for the help!

@Trihan
I'm sorry to bug you, but you mentioned that you had some ideas previously.
If it's not too time consuming for you, would you mind sharing them with me?

If it's too much, that's fine since I already got a great answer to my problem.
Sorry for the late reply.

@NotADev
Thank you very much, that is a great start.

But even though there is some variance between the numbers, there are some repeating trends happening.

For example when I ran
JavaScript:
distributeNumbers(300,3,125)
5 times, I got these results:
JavaScript:
[101, 115, 84]
[91, 119, 100]
[121, 101, 78]
[58, 123, 119]
[92, 111, 97]


So there is often one value in the 110 - 120 range and one value in the 80-100 range with the remaining value taking the rest.

However, this method *should* still suffice for now. So thank you again for the help!

@Trihan
I'm sorry to bug you, but you mentioned that you had some ideas previously.
If it's not too time consuming for you, would you mind sharing them with me?

If it's too much, that's fine since I already got a great answer to my problem.
I was playing with some ideas but I hit a roadblock on filling the elements with the "remaining" value after hitting the cap. If the answer works for you, that's fine. 🙂

The solution NotADev gave you is pretty much the same as what I was trying to do, I just hadn't finished implementing it.
But even though there is some variance between the numbers, there are some repeating trends happening.
Unfortunately, as long as you want to enforce a limit, there will not be a perfect solution. The problem lies in the fact that, due to the need for the sum of all the elements to be a specific number, it means that the elements are dependent upon each other.

For example, suppose we run distributeNumbers(100, 2). If the first element is randomly determined to be 20, then the next element absolutely has to be 80. There will never be a time that the first element is 20 and the second element isn't 80. So that means that the result of the second element is necessarily dependent upon the result of the first element.

As long as the first element is determined randomly, then technically, the second element was also determined randomly even though it is by a secondhand nature. What I mean is, there is the same chance to roll [0, 100] as there is to roll [100, 0] and the same chance to roll any combination (equal to 100) between. I probably didn't explain that well, but yeah... there's no bias one way or the other, as long as the randomness of the first element isn't being restricted.

On the other hand, if the first element isn't actually random, then the second element cannot be random either. And when you manually tamper with the possible results (such as by enforcing an arbitrary limit), you are restricting the randomness. For example, suppose that we run distributeNumbers(100, 2, 60). The first element obviously can't be above 60. But then when we consider that the second element also can't be above 60, then it means that the first element can't be below 40 (since the sum needs to be 100). So by enforcing a limit, you're restricting each element to a range from 40-60, and you won't see much variance.

This problem gets even worse as you lower the limit. For example, look at distributeNumbers(100, 2, 50)... There's only one possible outcome: [50, 50].

I probably just rambled a bunch and didn't explain my thoughts very well, but the TLDR is that you will be limiting the possible variance as you long as you insist on implementing an upper limit for each element, because if you enforce an upper limit on each element, then by necessity, you will also have to enforce a lower limit on at least some of the elements.

5 times, I got these results:
JavaScript:
[101, 115, 84]
[91, 119, 100]
[121, 101, 78]
[58, 123, 119]
[92, 111, 97]
If you are certain that you didn't make a typo here, then you might need to double check your code and make sure that there aren't any mistakes. It should be impossible to get a result of [91, 119, 100], because the sum of those numbers is 310.
Right now I'm not sure what a "perfect" number distribution would look like for your application.

As Anthran already said, the constraints you added will to some degree determine the numbers you can get. Adding to the first example, you could also run distributeNumbers(150, 3, 60). While the first number could theoretically be anything between 30 and 60, if you were to pick 30 then the two other numbers would obviously need to be 60, meaning that you'd already have at least twice as many 60s as 30s regardless of your desired distribution.

@Trihan
I currently can't think of a reason why it couldn't be 0.
So I doubt there is a need for a minimum, but then again, it might be nice to have a variant with a minimum for future reference. Only if it's not too much effort of course.
Unless you want to allow negative numbers 0 would be your minimum then. If you want a minimum of 30 for example, you could add 30 to your resulting array elements (and reduce your limit and value accordingly).

I'm sorry to bug you, but you mentioned that you had some ideas previously.
If it's not too time consuming for you, would you mind sharing them with me?
Some suggestions that may or may not be helpful here:

- Adding to NotADevs solution:

Not sure how useful this idea is, but to create a more even distribution you could try to restrict the number range for each roll so that the average outcome would match the "needed average roll":
For example in the case of distributeNumbers(300, 3, 125):
For the first roll, the "needed average" would be remaining value / remaining slots = 300 / 3 = 100, so considering the limit you would only roll a number between 75 and 125. The "needed average" would then be updated after each roll, so lower numbers may still occur if your first rolls are high enough.

I haven't tried out this approach much yet, but it might swing the result from "outliers are too prevalent" to "outliers are too rare" maybe, depending on what you want to see. It should not significantly increase the running time at least.

The modified code:
Spoiler
Code:
function distributeNumbers(value, length, limit = value) {
    let arr = [];
    let rest = value;
 
    // e.g. loops from element[0] -> element[1] if length = 3
    for (let i = 0; i < length - 1; i++) {
 
        // << This part differs from NotADevs solution >>
        // Restrict the number range so the average outcome is (remaining value / remaining length)
        // (This should also guarantee that the final remaining value is within the limit)
        let avgRoll = rest / (length - i);
        let minRoll = Math.max(0, Math.ceil(2 * avgRoll - limit));
        let maxRoll = Math.min(limit, Math.floor(2 * avgRoll));
 
        arr[i] = rnd_num(minRoll, maxRoll);
        rest -= arr[i];
    }
 
    // last element takes remaining value
    // e.g. element[2] if length = 3
    arr[length - 1] = rest;
 
    // SHUFFLE ARRAY HERE
 
    console.log(arr);
};


- Another option to give every feasible combination the same chance of occurring:

The idea is to determine the chances for each roll by the amount of possible combinations that would be left.
The easiest way to achieve that would be to create a table that stores the combinations to achieve X value with Y entries.
The current approach is rather slot (expected run time behaviour of O(length * value) due to creating the table of that size), but it might still be fine for smaller numbers.

Also, you might still see patterns you don't want to see, as in the case of distributeNumbers(150, 3, 100) for example, rolling a 50 would be more likely than either a 40 or a 60 due to the number of their combinations (in case you would rather see a more even distribution of values)

Somewhat complicated, and hopefully not too messed up code:
Spoiler
Code:
const randomlyDistribute = function(totalValue, slotCount, maxSlotValue = Infinity) {
    if (slotCount < 0 || totalValue < 0 || totalValue > (slotCount * maxSlotValue)) {
        return undefined;
    }
    // Create Look Up Table for possible combinations for each [remaining slots][target total]
    let combinationCountTable = new Array(slotCount);
    combinationCountTable[0] = [1];
    for (let remainingSlots = 1; remainingSlots < slotCount; remainingSlots++) {
        let oldTable = combinationCountTable[remainingSlots - 1];
        let newTable = new Array(Math.min(oldTable.length + maxSlotValue, totalValue + 1));
        newTable[0] = 1;
        for (let i = 1; i < newTable.length; i++) {
            let gainedCombinations = oldTable[i] || 0;
            let lostCombinations = oldTable[i - 1 - maxSlotValue] || 0;
            newTable[i] = newTable[i - 1] + gainedCombinations - lostCombinations;
        }
        combinationCountTable[remainingSlots] = newTable;
    }
    // ---
    let result = [];
    let rest = totalValue;
    for (let remainingSlots = slotCount; remainingSlots > 0; remainingSlots--) {
        let chances = [];
        for (let i = 0, max = Math.min(maxSlotValue, rest); i <= max; i++) {
            chances[i] = combinationCountTable[remainingSlots - 1][rest - i] || 0;
        }
        let diceRoll = Math.floor(Math.random() * chances.reduce((res, i) => res + i));
        let outcome = chances.findIndex(i => ((diceRoll -= i)) < 0);
        rest -= outcome;
        result.push(outcome);
    }
    return result;
};

The concept behind creating the table is "Dynamic Programming". Generally, the idea is to repeately break down a big problem into smaller ones.
For example, to determine the number of combinations to roll 20 with 5 dice, you can take one dice and sum up the combinations of rolling a 1 and then 19 with the other 4 dice, a 2 and 18 with the others, 3 and 17 with the others etc.
You can then break down the number of combinations of rolling X with 4 dice the same way until you are left with 1 dice or even 0.

When creating the table, you do the reverse by starting with the primitive case and building your more elaborate cases on top of it. With 0 dice you only have the option to roll a 0, with 1 dice you have one option to roll anything between the minimum and maximum each (the minimum in this case is also 0).
With 2 and more dice you have the sum of feasible combinations from the previous step after subtracting anything between minimum and maximum the value.


Would maybe need to come back to this, still hope this helps.

Edit: Small correction to the table algorithm (the table was one column short)
@Another Fen
Right now I'm not sure what a "perfect" number distribution would look like for your application.
Well, I am not actually looking for a 100% perfectly randomized distribution. I just need to have a
somewhat diverse amount of variance between the numbers I get as an output. That's why
I was perfectly fine with using @NotADev 's solution.




I guess it *would* be helpful to give some context behind all of this.
For the time being, I only intend to use this function for the following mechanic;

In the game, the player is regularly faced with a forked path with three or four routes to go as options. Each route yields different rewards at the end.

Each route also has a chance to spawn an enemy encounter along the way. And if there is an encounter, their strength is also randomized beforehand.

I intend to use the function of this thread to essentially randomize encounter chances and their strength (separately).

All of this will be given to the player as information so that they have to do some decision-making on which route to take.

So to translate this mechanic into the function:

The value describes the overall likelyhood of encounter / strength of enemies
The length describes the amount of possible ways you can go (the slot count)
The limit is mainly used in the encounter chance so it doesn't go over 100% or to eliminate extreme cases when calculating enemy strength.

So I could say
JavaScript:
var encounterChances = distributeNumbers(200,3,100);
when calculating the encounter chances of each path.
Then I can reference these values as I need:
JavaScript:
encounterChances[0]
encounterChances[1]
encounterChances[2]



With that being said, I don't really need hyper-complex algorithms with 100% efficiency.

I tested out the first function you gave me and I really like the results I'm getting.

The second function is also giving me promising results.

There may be better solutions and this algorithm is definitely not optimized, but this solution is probably going to be rather slow compared to your other options (expected run time behaviour of O(length * value) due to creating the table of that size), but it might still be fine for smaller numbers.
I'm probably never going above 3-digits in terms of value or limit. And its unlikely that there will be more than 4 or 5 slots. So that should be fine.

I'm probably going to do some more testing with both, but I'll probably stick with the first one.

Thank you very much for going out of your way to help!
Hello, old thread but I was working on a similar problem and thought I'd share my solution for funzies since I've never seen this discussed online before. My solution creates a list of random numbers from 0 to 1 such that they sum to half the length of the list. I use each number to interpolate between a min and a max for each stat. I chose half the length is the sum since I'm interpreting a 50% in everything as average.

The approach works by giving each element a random value such that the value is never so high it brings us past or limit, and never so low that the remaining elements can't pick up the slack. Variance between solutions grows as you work down the list (final values are typically high or low) so I shuffle the order to get nicer looking results.

Here is the code in Golang.

func RandomDist(Length int) []float64 {
//result
dist := make([]float64, Length)
//value we need to reach
totalLeft := float64(Length) / 2
//fill with default values
for i := 0; i < Length; i++ {
//ensure we don't end up with too much value
high := math.Min(totalLeft, 1)
//ensure we have enough so that we can reach our target by the end of the list
low := math.Max(0, totalLeft-float64(Length-i-1))
randValue := RandomFloat64(low, high)
dist[i] = randValue
totalLeft -= randValue
}
//shuffle the slice
for i := 0; i < Length; i++ {
j := rand.IntN(Length)
dist[i], dist[j] = dist[j], dist[i]
}
return dist
}
func RandomFloat64(min, max float64) float64 {
return min + (max-min)*rand.Float64()
}

Original thread: https://forums.rpgmakerweb.com/threads/distribute-a-value-randomly-among-an-array-but-with-limit.154139/