0

I have a bit of a complicated question. I'm currently trying to write a REALLY simple version of path finding, and to do that I need a way to generate number within a range, and each number must be different from all the others, and bigger than the last number. How would I go about doing this? So output would look like:

1,5,6,9,15,18

  • 1
    What is the range of numbers you want to random? Will you always need six numbers? – Pshemo Aug 25 '13 at 20:53
  • Depends on the distribution you want. Should this be a random sample of the given range, or should each number be uniformly distributed in the range between the previous number and the upper bound? – user2357112 Aug 25 '13 at 20:53

2 Answers2

1

Create a random generator function:

public static int randInt(int min, int max) {

    // Usually this can be a field rather than a method variable
    Random rand = new Random();

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

(code courtesy from an answer by Greg Case).

Call this wherever you want and check as like:

int a;

a=randInt(min,max);

and for the next time parse the previously generated value, like:

randInt(a,  max);
Community
  • 1
  • 1
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
  • 1
    Making a new generator on every call is a bad idea. You'll generate a new seed on every call and use it once; the seeds are likely to have undesirable properties, and it won't be as statistically sound as using a single generator (not that the default Java RNG is any good, but still). – user2357112 Aug 25 '13 at 20:59
0

Use reservoir sampling to pick n numbers from your range. Since you're going through the range in order the resulting list is sorted.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • It works, but it's way slower than it could be. To reservoir sample from the range of all ints, you'd have to iterate through all ints. A better algorithm would take time proportional to the size of the required sample. – user2357112 Aug 25 '13 at 20:56
  • Well, the question looked like small ranges. Ideally you'd pick either reservoir sampling or rejection sampling depending on how large *n* and *k* are for picking *n* numbers from (0, *k*). – Joey Aug 25 '13 at 21:46