开发者

how to get controlled random number in c#

I want to generate random numbers but controlled, meaning the numbers s开发者_如何转开发hould be nearly equally separated, and spread through the range.

As an example, if the bounds were 1 and 50, then if the first generated number is 40 then the next number should not be close. Suppose it's 20, then 30 would be an acceptable third number.

Please help.


Rather than completely random numbers, you might want to look at noise functions like Perlin Noise to generate superficially random data in a predictable fashion.

http://en.wikipedia.org/wiki/Perlin_noise

There are a few variations out there - definitely worth researching if you can describe your segmentation of data algorithmically.

It's used a lot in gaming to smooth and add interest to otherwise randomly generated terrain textures.

There's a few sample implementations in C# out there, this one is used to generate a bitmap but could easily be adapted to fill a 2d array:

http://www.gutgames.com/post/Perlin-Noise.aspx

There's also plenty of questions here on SO about Perlin Noise too:

https://stackoverflow.com/search?q=perlin+noise


You may do something like this:

randomSpaced[interval_, mindistance_, lastone_] :=
         (While[Abs[(new = RandomReal[interval])-lastone] < mindistance,];
          Return[new];)  

Randomnicity test drive:

For[i = 1, i < 500000, i++,
  rnd[i] = randomSpaced[{0, 40}, 10, rnd[i - 1]];
  ];
Histogram[Table[rnd[i], {i, 500000}]]  

how to get controlled random number in c#

You may see that the frequencies accumulates in the borders

Moreover, if you are not cautious, and ask for a distance too high, the results will be something like:

For[i = 1, i < 50000, i++, 
  AppendTo[rnd, randomSpaced[{0, 40}, 25, Last[rnd]]];];
   Histogram[rnd

]

how to get controlled random number in c#

because you are not allowing points at the center.


Define a separation distance d the new number should have to the last. If the last number was, say, 20 the next random number should not be from 20-d to 20+d. That means the random interval should be [1, 20-d) and (20+d,50].

Since you can not call random.next() with two intervals you need to call it with an interval reduced by 2d and then map the random number to your original [1,50] interval.

static class RandomExcludingSurrounding
{
    static Random random = new Random();

    public static int Next(int x, int d, int min, int max)
    {
        int next = random.Next(min, max-2*d);
        if (next > x-d)
            next += 2*d;
        return next;
    }
}

int min = 1;
int max = 50;
Random random = new Random();
int next = random.Next(min, max);

while(true)
{
    int next = RandomExcludingSurrounding.Next(next, 20, min, max);
    Console.WriteLine(next);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜