简体   繁体   中英

Randomly generated numbers in a basic array

I simply need to know what i should do to make so that a basic array is filled with randomly generated numbers. now i know how to do that, what i don't know how to to do is to make it so that the randomly generated numbers are bigger than the last number generated all the way through to the end of the array.

Just generate for the list, and then sort them smallest to largest.

for(int i = 0; i < arr.length; ++i) {
    arr[i] = Random.nextInt(100);
}
Arrays.sort(arr);

Generate random numbers, and then sort the array.
You can sort the array using Arrays.sort()

It doesn't make sure that each number is strictly bigger then the previous numbers [it only gurantees <= ], so if it is an issue - you will have to make sure you have no dupes in the generated numbers.

您可以生成一个随机数数组,然后使用Array sort对其进行排序

There was a comment on the question, I lost the author's name, that recommended adding the randomly generated number to the previous number, which I thought was an interesting approach.

arr[0] = Random.nextInt(100);

for(int i = 1; i < arr.length; ++i) {
    arr[i] = arr[i-1] + Random.nextInt(100); 
} 

This removes the need to sort your result array.

I'm surprised no one mentioned that we can use SecureRandom API to easily generate random arrays without manually populating it .

For ex. generating a random array of size 100 :

SecureRandom random = new SecureRandom();
int arr[] = random.ints(100).toArray();

BTW this should be possible from java 8 onwards.

You can have your own algorithm of generating incremental...

For example...

Random each time and add that number to the last one :)

Random class in java does not allow you to have a minim limit where to start.. only one...

For example:

myArray[0] = Random.nextInt(10000);
for(int i=1; i<myArray.length; i++)
{
    myArray[i] = myArray[i-1]+Random.nextInt(10000);
}

So.. it's random and you don't have to sort it.. try keeping everything simple...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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