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

时间:2013-11-14 07:30:42

标签: java

我想按升序生成随机数,例如: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;
}

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

3 个答案:

答案 0 :(得分:3)

/**
 * 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按升序排序”),因为它会修改每个连续数字的范围。 (像任何其他不需要排序的解决方案一样)

答案 1 :(得分: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;
}

答案 2 :(得分: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++;
        }
    }

}