2

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

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

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

我怎样才能达到上述目标?

4

3 回答 3

4
/**
 * 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;
}

你可以像这样使用它:

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

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

/**
 * 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;
}

用例:

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

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

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

于 2013-11-14T07:36:36.183 回答
2

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;
}
于 2013-11-14T08:19:33.893 回答
1

那这个呢?

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

}
于 2013-11-14T07:49:22.983 回答