Generating a set of random numbers such that their sum falls within a range

69 Views Asked by At

I'm sure this is something that I should be able to google but for some reason, I just can't structure my question properly...

Basically: Given a set of size N, I need to generate numbers between A and B and ensure that the resulting sum of the set falls between X and Y.

For example: Generate 3 numbers between 0 and 1 such that the sum falls between 2.4 and 3.

I've figured out that I need to generate random numbers between MIN and MAX and each step, I need to recalculate MIN (depending on choices made and amount of numbers left in the set)...but this is honestly starting to feel like a wasted effort after a few hours of struggling.

I'm not really expecting an answer here (definitely not expecting someone to write the algorithm) but I'm hoping someone can point me in the direction of other problems that I can read about that might jostle something in my head.

1

There are 1 best solutions below

1
On

Alright. After some sleep, my mind is working a bit better again. Solved it this morning (with some simplification of the problem space)

For my purposes, the max roll (B) is always (Y / N) and the min roll (A) is always 0.

Here's the algorithm (in JavaScript):

const calculateSet = (setSize, minSum, maxSum) => {
    const maxRoll = maxSum / setSize;

    const set = [];

    let runningTotal = 0;

    for (let i = 0; i < setSize; i++) {
        const localMin = Math.max(0, minSum - runningTotal - ((setSize - (i + 1)) * maxRoll));

        let roll = localMin + (Math.random() * (maxRoll - localMin));

        runningTotal += roll;

        set.push(roll);
    }

    return set;
};

Basically, for every roll, we posture that we roll a zero. How far off the minSum (X) would we be if all consecutive rolls are maxRolls (B). If we're below minSum, we add this delta to localMin.

This algorithm can fairly easily be adapted to solve the full problem, but this is left as an exercise to the reader ;)

Here's a working pen of the algorithm in action: codepen.io