简体   繁体   English

增加随机生成的数字

[英]Increaing Randomly Generated Numbers

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.. 假设我从3开始,我希望下一个始终大于3。并说我生成了5,我希望下一个大于5,依此类推。

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;

}
int rnd = 0;
while (true) {
    rnd = ThreadLocalRandom.current().nextInt(rnd +1, Integer.MAX_INT);
    System.out.println("Next random: "+rnd);
}

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;

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);
        }
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM