-1

I want to create a random integer array in Java (min & max), but I want each randomly generated number to have an offset distance between every other.

I.e. Let's suppose that I want to create an array list containing 10 integer numbers between 20 and 100 that the offset/distance should be 5. The array might be 21, 28, 35, 52, 58, 65, 72, 80, 86, 95.

Thanks a lot

  • 1
    What do you mean with "the offset/distance should be 5"? In your example you have more than distance 5 between 35 and 52 for instance. – aioobe Mar 21 '16 at 08:09
  • I mean that every number should have at least 5 integers difference with every other. – Periplanomenos Mar 23 '16 at 10:52
  • Pick 10 random (but different) integers in the range 2 to 20 (see for instance [this](http://stackoverflow.com/q/158716/276052)) and then multiply each number by 5. – aioobe Mar 23 '16 at 11:08

1 Answers1

0

The simple variant (without handling overflows) :

int min;
int max;
int offset;

public int getRandomNumber(int current) {
    int curMin = current - offset;
    if (curMin < min)
        curMin = min;
    int curMax = current + offset;
    if (curMax > max)
        curMax = max;
    return curMin + (int) ( Math.random() * (curMax - curMin + 1));
}

And to get the first number:

int first = min + (int) ( Math.random() * (max - min + 1));
Gregory Prescott
  • 574
  • 3
  • 10