Generate N random numbers within a range with a constant sum
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
To generate N random numbers inside a range while forcing their total to equal a fixed sum, you have to satisfy both local bounds and a global constraint at the same time. The most important first step is checking whether the request is even feasible, because no algorithm can produce a solution when the sum lies outside the total allowed range.
Feasibility Comes First
For integer values in the interval [low, high], a solution exists only if:
N * low <= target_sum <= N * high
Example:
- '
N = 5' - '
low = 2' - '
high = 7' - '
target_sum = 18'
This is feasible because 5 * 2 = 10 and 5 * 7 = 35, and 18 lies between them.
If the target sum is outside that interval, stop immediately and report failure.
A Simple Constructive Algorithm
For integers, a practical approach is to build the numbers one by one. At each step:
- choose a random value for the current slot
- keep enough sum available for the remaining slots
- keep the remaining slots within their own bounds
That means the choice for each number is constrained by what must still be possible afterward.
This guarantees:
- each value stays in range
- the final sum is exact
Why Those Bounds Work
Suppose you are filling one position and still have remaining_slots - 1 positions left afterward. If you choose too small a value now, the remaining slots may be unable to reach the target sum even if all of them take the maximum allowed value. If you choose too large a value now, the remaining slots may be forced below the minimum allowed value.
That is why the current slot is limited to:
- at least
remaining_sum - (remaining_slots - 1) * high - at most
remaining_sum - (remaining_slots - 1) * low
The algorithm is random, but every random choice is filtered through feasibility for the rest of the sequence.
Integer Solutions Are Not Automatically Uniform
The algorithm above produces valid random solutions, but it does not sample every valid vector with equal probability. For many applications that is completely fine. If you need a truly uniform distribution over all valid integer solutions, the problem becomes more specialized and often requires dynamic programming or combinatorial counting.
So be clear about the requirement:
- valid random solution
- uniformly random valid solution
Those are different tasks.
Floating-Point Variant
For real numbers rather than integers, a common trick is:
- shift the problem so the lower bound becomes zero
- generate random proportions
- scale them to the remaining sum
- add the lower bound back
That works when the target is feasible. A simple example:
This version may need retries because scaling random weights can overshoot the upper bound on some coordinates.
Practical Uses
This pattern appears in:
- budget allocation simulations
- randomized test-data generation
- load-distribution experiments
- game-stat generation under caps
The important thing is to define whether the numbers are integers or real values before choosing the algorithm.
Common Pitfalls
- Forgetting the feasibility check and debugging an impossible request as if the generator were broken.
- Using a naïve "generate random values, then normalize" approach for integers, which usually breaks the range constraints after rounding.
- Assuming the sequential constructive algorithm is uniform over all valid solutions when it is only guaranteed to produce valid random solutions.
- Mixing integer and floating-point requirements without noticing that the algorithms and edge cases are different.
- Ignoring the final remaining-sum logic and choosing early values that make the rest of the sequence impossible to complete.
Summary
- A valid generator must satisfy both per-value bounds and the total-sum constraint.
- Always check feasibility first with
N * low <= target_sum <= N * high. - For integers, a sequential constrained-random algorithm is simple and reliable.
- For floating-point values, scaling random weights can work, but upper-bound handling needs care.
- "Random valid" and "uniform over all valid solutions" are different requirements and should not be confused.
Related reading
- Generate Non-Degenerate Point Set in 2D - C
- Generate random permutation of huge list in Python
- Generate Unique ID from Alphanumeric String
- Generating a pseudorandom binary sequence where the same number does not occur more than twice in a row
- Generating a random DAG
- Generating a random, non-repeating sequence of all integers in .NET
- Generating a tower defense maze longest maze with limited walls - near-optimal heuristic?
- Generating all combinations of elements in a single array in pairs

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.