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)