Java 如何按递增顺序生成随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19971987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:58:06  来源:igfitidea点击:

How to genearte the random number in increasing order

java

提问by Tamanna Iruu

I would like to generate random numbers in ascending order, for instance: 0, 2, 3, 5 .. 100, but not 2, 0, 5 ..

我想按升序生成随机数,例如:0, 2, 3, 5 .. 100,但不是2, 0, 5 ..

This is what I came up with so far:

这是我到目前为止想出的:

public static int vol=5;    
public static void main(String[] args) {
    int randno = getRandNum();
    vol = vol+randno;   
    System.out.println(getRandNum());
}   
private static  int getRandNum() {
    Random r = new Random();
    for (int i =0; i<10; i++)
    {
        int v=r.nextInt(vol);
        System.out.println("r"+v);
    }
    return vol;
}

How could I achieve the goal stated above?

我怎样才能实现上述目标?

回答by Ben Barkay

/**
 * Generates random numbers, returning an array of ascending order.
 * @param amount    The amount of numbers to generate.
 * @param max       The maximum value to generate.
 * @return  An array of random integers of the specified length.
 */
public static int[] generateIncreasingRandoms(int amount, int max) {
    int[] randomNumbers = new int[amount];
    Random random = new Random();
    for (int i = 0; i < randomNumbers.length; i++) {
        randomNumbers[i] = random.nextInt(max);
    }
    Arrays.sort(randomNumbers);
    return randomNumbers;
}

You could use it like so:

你可以像这样使用它:

// Generates 10 random numbers of value 0 to 100,
// printing them in ascending order
for (int number : generateIncreasingRandoms(10, 100)) {
    System.out.print(number + " ");
}


Or if you're a micro-optimization kind of person and do not wish to sort,

或者如果你是一个微优化类型的人并且不想排序,

/**
 * Generates random numbers, returning an array of ascending order.
 * @param amount    The amount of numbers to generate.
 * @param max       The maximum value to generate.
 * @return  An array of random integers of the specified length.
 */
public static int[] generateIncreasingRandomWithoutSorting(int amount, int max) {
    int[] randomNumbers = new int[amount];
    double delta = max / (float)amount;
    Random random = new Random();
    for (int i = 0; i < randomNumbers.length; i++) {
        randomNumbers[i] = (int)Math.round(i*delta + random.nextDouble() * delta);
    }
    return randomNumbers;
}

Use case:

用例:

// Generates 10 random numbers of value 0 to 100,
// printing them in ascending order
for (int number : generateIncreasingRandomWithoutSorting(10, 100)) {
    System.out.print(number + " ");
}

The reason that each number is between 0-10, 10-20, 20-30.. in this use case is that if I simply allow for the entire range and you get a 100 on the first try you're going to end up with an entire array of 100s.

在这个用例中,每个数字都在 0-10、10-20、20-30 之间的原因是,如果我只是允许整个范围并且你在第一次尝试时得到 100 你最终会整个数组有 100 个。

Being more controlled, with this solution you are not really getting what you're asking for ("10 numbers of 0 to 100 sorted ascendingly") since it modifies the range for each consecutive number. (like any other solution that doesn't require sorting)

受到更多控制,使用此解决方案,您并没有真正得到您所要求的(“0 到 100 的 10 个数字升序排列”),因为它修改了每个连续数字的范围。(就像任何其他不需要排序的解决方案一样)

回答by Manoj Awasthi

what about this?

那这个呢?

public class increasing {
    public static void main (String[] args) { 
        Random r = new Random(); 

        int totalNums = 100; 
        int count = 0;

        int lastVal = 0;
        int currVal = 0;
        while(count < totalNums) { 
            currVal = r.nextInt(200);
            lastVal = lastVal + currVal; 
            System.out.println(lastVal + ",");
            count++;
        }
    }

}

回答by mvieghofer

Ben Barkay's answer is good, but if you don't want to create a set of numbers in one step, but you want to get one number after another, you can do something like this:

Ben Barkay 的回答很好,但是如果您不想一步创建一组数字,而是想一个接一个地得到一个数字,则可以执行以下操作:

private static final int MAX = 5;

private Random rand = new Random();
private int maxRand = 0;

public int getIncreasingRandomNumber() {
    maxRand = rand.nextInt(MAX);
    return maxRand;
}