Determine the separation distance d, which the new number should have to the last. If the last number was, say, 20, the next random number should not be from 20 to 20 + d. This means that the random interval must be [1, 20-d) and (20 + d, 50].
Since you cannot call random.next () at two intervals, you need to call it at an interval reduced by 2d, and then map the random number to the original interval [1.50].
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);
}
source
share