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?
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.
Your code could be modified to look like this:
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.
If you need generate numbers with intervals, it can be just like that:
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"
For example:
In Java 8, if you want to have a
list
of non-repeatingN
random integers inrange (a, b)
, whereb
is exclusive, you can use something like this:How about this?
The user can then iterate through the
Set
using a for loop.