how to generate random numbers that adds up to certain value

  • Thread starter Thread starter DAXU
  • Start date Start date
D

DAXU

Hi,
I need to generate a fixed number of random integers that their
summary equals to certain values.
For example, the scenario can be:
simulate user hits (e.g. 20000) within a hour (3600 seconds).
the hits need to be random (e.g. five can be in second one, then 0
for seconds 2-4, another 10 at second 5 and so on)

I haven't really figure out the best way to do this.

Can someone help me?

Many Thanks

Jerry
 
Well, I am getting ready to live work so I slapped something together
hopping it will do what you need and it not buggy :)

class Program
{
static void Main(string[] args)
{
int hits = 2000;
int seconds = 3600;

int[] randomHits = new int[seconds];

Random rd = new Random();
int accumulatedHits = 0;
while (true)
{
int randomSec = (int)(rd.NextDouble() * (double)(seconds -
1));
randomHits[randomSec] += 1;
accumulatedHits++;

if (accumulatedHits == hits)
break;
}
}
 
DAXU said:
I need to generate a fixed number of random integers that their
summary equals to certain values.
For example, the scenario can be:
simulate user hits (e.g. 20000) within a hour (3600 seconds).
the hits need to be random (e.g. five can be in second one, then 0
for seconds 2-4, another 10 at second 5 and so on)

I haven't really figure out the best way to do this.

I would do something like:

Random rng = new Random();
int[] a = new int[3600];
for(int i = 0; i < 20000; i++)
{
a[rng.Next(a.Length)]++;
}

Arne
 
DAXU said:
Hi,
I need to generate a fixed number of random integers that their
summary equals to certain values.
For example, the scenario can be:
simulate user hits (e.g. 20000) within a hour (3600 seconds).
the hits need to be random (e.g. five can be in second one, then 0
for seconds 2-4, another 10 at second 5 and so on)

I haven't really figure out the best way to do this.

Can someone help me?

Many Thanks

Jerry

you could generate a list of random numbers the usual way,
then sum them, then adjust them by the necessary amount,
either by multiplying them all by the right factor,
or by adding or subtracting 1 from random numbers.

Colin =^.^=
 
Thanks for everyone's reply.

It is not a scientific research and the requirement is not strict
(used as am internal tool). I think the solutions here are already
enough for me. Many Thanks
 
Back
Top