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