0

I want to generate random integers such that the next generated number is always greater than the previous one.

Assume I start with 3, I want the next to be always greater than 3. And say I generated 5, I want the next to be greater than 5 and so on..

Kaleb Blue
  • 487
  • 1
  • 5
  • 20
  • Is there a top limit or is the next number allowed to be 40,000,000 etc.? – RealSkeptic Mar 06 '15 at 18:42
  • I would take a look here: http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java – SimplyPanda Mar 06 '15 at 18:43
  • What kind of randomness do you expect? Do you want each integer within the range to be selected with the same probability? Or you just need any increasing number sequences? – Eric Mar 06 '15 at 19:59

4 Answers4

4

This should get you a number that is consistently larger than the previous value. The range is the maximum distance from the previous value that you want the number to be.

public getLargerRandom(int previousValue){
    int range = 100; //set to whatever range you want numbers to have

    return random.nextInt(range) + previousValue;

}
Davis Broda
  • 4,102
  • 5
  • 23
  • 37
0
int rnd = 0;
while (true) {
    rnd = ThreadLocalRandom.current().nextInt(rnd +1, Integer.MAX_INT);
    System.out.println("Next random: "+rnd);
}
Uli
  • 1,390
  • 1
  • 14
  • 28
0

You would store the randomly generated number as a variable, then use that as a minimum value for the next generation of numbers.

int x = 0;
x = new Random.nextInt(aNumber) + x;
CaffeineToCode
  • 830
  • 3
  • 13
  • 25
0

The following example generates a set of random numbers between a start value and a max value without going over the desired maximum number.

import java.util.Random;

public class RandomNumbers {
  public static void main(String[] args) {
    GetIncreasingInts(20, 3, 101);
    }

  public static void GetIncreasingInts(int numIntsToGet, int start, int max) {
    if (numIntsToGet > 0 && start >= 0 && max > 0) {
      Random random = new Random();
      int nextStart = start;
      int num = -1;

      for (int index = 0; index < numIntsToGet; index++) {
        if ((max - 1) <= nextStart)
          break;
        else {
          num = nextStart + random.nextInt(max - nextStart);
          nextStart = num;

          System.out.println("Number: " + num);
        }
      }
    }
  }
}