可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to create a set of random numbers without duplicates in Java.
For example I have an array to store 10,000 random integers from 0 to 9999.
Here is what I have so far:
import java.util.Random;
public class Sort{
public static void main(String[] args){
int[] nums = new int[10000];
Random randomGenerator = new Random();
for (int i = 0; i < nums.length; ++i){
nums[i] = randomGenerator.nextInt(10000);
}
}
}
But the above code creates duplicates. How can I make sure the random numbers do not repeat?
回答1:
Integer[] arr = {...};
Collections.shuffle(Arrays.asList(arr));
For example:
public static void main(String[] args) {
Integer[] arr = new Integer[1000];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));
}
回答2:
A simple algorithm that gives you random numbers without duplicates can be found in the book Programming Pearls p. 127.
Attention: The resulting array contains the numbers in order! If you want them in random order, you have to shuffle the array, either with Fisher–Yates shuffle or by using a List and call Collections.shuffle()
.
The benefit of this algorithm is that you do not need to create an array with all the possible numbers and the runtime complexity is still linear O(n)
.
public static int[] sampleRandomNumbersWithoutRepetition(int start, int end, int count) {
Random rng = new Random();
int[] result = new int[count];
int cur = 0;
int remaining = end - start;
for (int i = start; i < end && count > 0; i++) {
double probability = rng.nextDouble();
if (probability < ((double) count) / (double) remaining) {
count--;
result[cur++] = i;
}
remaining--;
}
return result;
}
回答3:
Achintya Jha has the right idea here. Instead of thinking about how to remove duplicates, you remove the ability for duplicates to be created in the first place.
If you want to stick with an array of ints and want to randomize their order (manually, which is quite simple) follow these steps.
- create array of size n.
- loop through and initialize each value at index i to the value i (or i+1 if you wish to have the numbers 1 to n rather than 0 to n-1).
- finally, loop through the array again swapping each value for a value at a random index.
Your code could be modified to look like this:
import java.util.Random;
public class Sort
{
// use a constant rather than having the \"magic number\" 10000 scattered about
public static final int N = 10000;
public static void main(String[] args)
{
//array to store N random integers (0 - N-1)
int[] nums = new int[N];
// initialize each value at index i to the value i
for (int i = 0; i < nums.length; ++i)
{
nums[i] = i;
}
Random randomGenerator = new Random();
int randomIndex; // the randomly selected index each time through the loop
int randomValue; // the value at nums[randomIndex] each time through the loop
// randomize order of values
for(int i = 0; i < nums.length; ++i)
{
// select a random index
randomIndex = randomGenerator.nextInt(nums.length);
// swap values
randomValue = nums[randomIndex];
nums[randomIndex] = nums[i];
nums[i] = randomValue;
}
}
}
And if I were you I would likely break each of these blocks into separate, smaller methods rather than having one large main method.
Hope this helps.
回答4:
If you need generate numbers with intervals, it can be just like that:
Integer[] arr = new Integer[((int) (Math.random() * (16 - 30) + 30))];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));`
The result:
[1, 10, 2, 4, 9, 8, 7, 13, 18, 17, 5, 21, 12, 16, 23, 20, 6, 0, 22, 14, 24, 15, 3, 11, 19]
Note:
If you need that the zero does not leave you could put an \"if\"
回答5:
How about this?
LinkedHashSet<Integer> test = new LinkedHashSet<Integer>();
Random random = new Random();
do{
test.add(random.nextInt(1000) + 1);
}while(test.size() != 1000);
The user can then iterate through the Set
using a for loop.
回答6:
In Java 8, if you want to have a list
of non-repeating N
random integers in range (a, b)
, where b
is exclusive, you can use something like this:
Random random = new Random();
List<Integer> randomNumbers = random.ints(a, b).distinct().limit(N).boxed().collect(Collectors.toList());
回答7:
public class Randoms {
static int z, a = 1111, b = 9999, r;
public static void main(String ... args[])
{
rand();
}
public static void rand() {
Random ran = new Random();
for (int i = 1; i == 1; i++) {
z = ran.nextInt(b - a + 1) + a;
System.out.println(z);
randcheck();
}
}
private static void randcheck() {
for (int i = 3; i >= 0; i--) {
if (z != 0) {
r = z % 10;
arr[i] = r;
z = z / 10;
}
}
for (int i = 0; i <= 3; i++) {
for (int j = i + 1; j <= 3; j++) {
if (arr[i] == arr[j]) {
rand();
}
}
}
}
}
回答8:
HashSet<Integer>hashSet=new HashSet<>();
Random random = new Random();
//now add random number to this set
while(true)
{
hashSet.add(random.nextInt(1000));
if(hashSet.size()==1000)
break;
}