简体   繁体   English

基本数组中随机生成的数字

[英]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() 您可以使用Arrays.sort()对数组进行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 . 没有人感到惊讶的是,我们可以使用SecureRandom API轻松生成随机数组, 而无需手动填充它

For ex. 对于前。 generating a random array of size 100 : 生成大小为100的随机数组:

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

BTW this should be possible from java 8 onwards. 顺便说一句,从Java 8开始应该是可能的。

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... Java中的Random类不允许您限制从哪里开始..只有一个...

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... 所以..它是随机的,您不必对其进行排序..请尝试使所有内容保持简单...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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