eageranalyst
eageranalyst

Reputation: 1026

Generate random numbers within individual ranges that sum to a value

I am trying to automatically generate a large set of test data and I am struggling to understand how to generate a set of random values required.

I need to create a set of random values which occur within different ranges. The sum of the resulting values must be over or under a predetermined value depending on the test case.

For example,

Value | Minimum value | Maximum Value
A | 100 | 300
B | 200 | 500
C | 300 | 600
D | 100 | 300

If the sum of values must be greater than 800 a valid solution would be

A = 200
B = 400
C = 500
D = 100

If the sum of values must be less than 800 a valid solution would be

A = 100
B = 200
C = 300
D = 100

Can this problem only be solved using an optimisation function? Is there any other way to calculate the values of ABCD?

I am looking to solve this problem using SQL but would be interested to hear a pseudo-code approach too.

Upvotes: 2

Views: 1935

Answers (2)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

Try and try again until you get what you want.

declare @T table (Value char(1), MinValue int, MaxValue int)
insert into @T values('A', 100, 300)
insert into @T values('B', 200, 500)
insert into @T values('C', 300, 600)
insert into @T values('D', 100, 300)

declare @R table (Value char(1), Rnd int)

declare @Sum int

while 0=0
begin
    delete @R
    insert into @R
    select Value, round(((MaxValue - MinValue -1) * rand() + MinValue), 0) as Rnd
        from @T

    select @Sum = sum(Rnd) from @R
    if @Sum > 800
        break
end

select *, @Sum
from @R

Upvotes: 2

smirkingman
smirkingman

Reputation: 6358

Generate 4 random numbers, A, B, C, D.

Sum them, =E

Scale A,B,C,D by E/desired total.

Upvotes: 0

Related Questions